Explore JavaScript String objects in depth

  • 2020-05-12 02:11:24
  • OfStack

String string object

1. Introduction

The String object performs operations on a string, such as intercepting a substring, finding a string/character, converting case, and so on.

2. Definition

2.1 new String(Value) constructor: returns an String object whose content is Value
Parameters:

value {String} : string

The return value:

{String object} returns an String object whose content is Value

Example:


var demoStr = new String('abc');
console.log(typeof demoStr); // => object
console.log(demoStr); // => abc

2.2 direct assignment (recommended)
Example:


var demoStr = 'abc';
console.log(typeof demoStr); // string
console.log(demoStr); // => abc

3. Instance properties

3.1 length: returns the number of characters in a string


var s = 'abc';
console.log(s.length); // => 3
console.log(' Happy New Year! '.length); // => 4 : 1 Four Chinese characters are also calculated as 1 A number of
console.log(''.length); // => 0 : returns an empty string 0

4. Instance method

Note: the instance method of the string does not change the string itself, only returns the result of the operation.

4.1 charAt(index) : returns the character at the specified position in a string, starting from 0. If a nonexistent value is passed in, an empty string is returned
Parameters:

index {int} : position index, calculated from 0

The return value:

{string} returns the character at the specified position in a string; If you pass in a nonexistent position value, return an empty string

Example:


var s = 'abc';
console.log(s.charAt(1)); // => b : returns the position as 1 The character of
console.log(s); // => It doesn't affect the original array
console.log(s.charAt(5)); // => '' : get 1 Zero characters that do not exist 1 A length of 0 Empty string of

4.2 charCodeAt(index) : returns the Unicode encoding of the specified position character in a string
Parameters:

index {int} : index of position, calculated from 0

The return value:

{number} returns the Unicode encoding of the specified position character in a string; If a nonexistent location value is passed in, NaN is returned

Example:


var s = 'abc';
console.log(s.charCodeAt(0)); // => 98 Character: b the Unicode coding
console.log(s.charCodeAt(5)); // => NaN : get 1 Zero characters that do not exist NaN

4.3 concat (value1 value2... valueN) : concatenates one or more strings and returns the concatenated string
Parameters:

1) value1 value2... valueN {string} : 1 or more strings

The return value:

{string} returns the string after the connection

Example:


var s = 'abc';
console.log(s.concat('d')); // => abcd
console.log(s); // => abc : does not affect the original string
console.log(s.concat('d', 'e')); // => abcde

4.4 indexOf(value, |startPosition) : look up a string or character from front to back in the instance and return the position found (count from 0). If not, return negative 1
Parameters:

value {string} : the search string

startPosition {int} optional: the starting position to start the search, the default starting position is 0

The return value:

{int} returns the position found (count from 0). If not, return negative 1

Example:


var s = 'abc';
console.log(s.indexOf('b')); // => 1
console.log(s.indexOf('d')); // => -1 : not found
console.log(s.indexOf('b', 2)); // => -1 Position: from 2( The first 3 A character ) Start looking for

4.5 lastIndexOf(value, |startPosition) : look up a string or character from the back in the instance and return the position found (count from 0). If not, return negative 1
Parameters:

value {string} : the search string

startPosition {int} optional: the starting position to start the search. The default is to start the search at the end

The return value:

{int} returns the position found (count from 0). If not, return negative 1

Example:


var s = 'abcabc';
console.log(s.lastIndexOf('a')); // => 3 : look backwards and forwards
console.log(s.lastIndexOf('d')); // => -1 : not found back -1
console.log(s.lastIndexOf('a', 2)); // => 0 Position: from 2( The first 3 A character ) Start looking ahead

4.6 localeCompare(value) : compare the instance with the parameter and return the comparison result
Parameters:

value {string} : string to compare

The return value:

0: the instance is larger than the parameter

1: the instance is equal to the parameter

-1: the instance is smaller than the parameter

Example:


var s='abc';
console.log(s.localeCompare('ab')); // => 1 : the instance is larger than the parameter
console.log(s.localeCompare('abc')); // => 0 : the instance is equal to the parameter
console.log(s.localeCompare('abd')); // => -1 : the instance is smaller than the parameter

4.7 match(regexp) : use regular expressions for match lookups
Parameters:

regexp {regexp} : regular expression, eg: /\d+/

The return value:

Returns different results depending on whether the regular expression has the attribute 'g'; If there is no match, return {null} :

Regular expression without the attribute 'g', perform 1 match, return {single match} result object, the object contains the following properties:

Array number: represents the matching result, 0 is the matching text, 1 is the matching result from the first parentheses on the right, 2 is the second parentheses, and so on

index property: represents the matching text at the beginning of the matching source

input property: represents the matching source

The regular expression with the attribute 'g', perform global matching, find all the matching objects of the string, return 1 {string array} : the array element contains every matching object in string, does not contain the string in the regular expression parentheses, and does not provide index and input attributes.

Example:


// 1. A single match
var s = 'a1b2c3d4';
var mc = s.match(/\d+/); // => For the first 1 The results of a regular match
if (mc != null) {
    console.log(mc.index); // => 1 : the matching result is at the starting position of the matching source
    console.log(mc.input) // => a1b2c3d4 Matching the source:
    console.log(mc[0]); // => 1 : get the matched result
}
// 2. The global matching
var mcArray = s.match(/\d+/g); // => Gets all the regular matching Numbers
if (mcArray != null) {
    for (var i = 0,len=mcArray.length; i < len; i++) {
        var mc=mcArray[i];
        console.log(mc); // => 1,2,3,4 : get the matched result
    }
}
// 3. Match with parentheses
s = 'a1b2c3d4';
mc = s.match(/[a-z]([1-9])/); // => For the first 1 The results of a regular match
if (mc != null) {
    console.log(mc.index); // => 0 : the matching result is at the starting position of the matching source
    console.log(mc.input) // => a1b2c3d4 Matching the source:
    console.log(mc[0]); // => a1 : the serial number 0 Represents the result of a match
    console.log(mc[1]); // => 1 : the serial number 1 According to the first 1 The result of a child match in parentheses
}

4.8 replace(regexp, replaceStr) : replaces the substring matched by the regular expression and returns the replaced string
Parameters:

regexp {regexp} : regular expression. eg: / \ d + /

replaceStr {string | function} :

1) if it is a string, it represents the replacement string, which is replaced by the string matching to the string;

The $character in a string has a special meaning:

$1, $2... $99: represents the matching subitem of the parenthesis from left to right

$& : represents the entire parameter matching subitem

$$: the dollar sign

2) if it is a function, it means that every matching result will call this function. The only parameter of the function is the matching result, and a replacement result will be returned.

The return value:

{string} returns a replaced string

Example:


var oldStr = 'a1b2c3d4';
// 1. Regex matches to [all] Numbers, replaced by: ',' The comma
var newStr = oldStr.replace(/\d+/g, ',');
console.log(newStr); // => a,b,c,d,
// 2. A regular match to [all] Numbers, replaced with: match result + ',' The comma
newStr = oldStr.replace(/\d+/g, '$&,');
console.log(newStr); // => a1,b2,c3,d4,
// 3. Regex matches to [all] Numbers, and each match calls the function and returns the replaced result
newStr = oldStr.replace(/\d+/g, function (word) {
    if (word % 2 == 0) {
        return ' accidentally ';
    }
    return ' p. ';
});
console.log(newStr); // => a p. b accidentally c p. d accidentally

4.9 search(regexp) : returns the position where the first match of the regular expression is found
Parameters:

regexp {regexp} : regular expression. eg: / \ d + /

The return value:

{int} returns the position of the first matched result; Returns -1 if no match is found

Example:


console.log( 'abcd'.search(/\d+/) ); // => -1 No figures were found
console.log( 'abcd1234'.search(/\d+/) ); // => 4 : position serial no 4 To return to the first 1 The position of the Numbers

4.10 slice(start, |end) : returns a substring from the start position to the first position of end
Parameters:

start {int} : index of the starting position of the substring extraction (including the characters of this position).

If the number is negative, it starts at the end of the string. For example, -1 means the reciprocal of a string, and -2 means the reciprocal of the second character.

end {int} optional: index of the end position extracted from the substring (excluding the characters of this position).

If the number is negative, it starts at the end of the string. For example, -1 means the reciprocal of a string, and -2 means the reciprocal of the second character.

If this parameter is omitted, all characters from the start position to the end are returned.

Note:

Substrings are extracted from left to present, and an empty string is returned if the start index position is greater than the end index position.

The return value:

{string} returns a substring from the start position to the first position of end.

Example:


var s = 'abcdefg';
console.log( s.slice(1) ); // bcdefg : omit end Parameter, ending at the end
console.log( s.slice(1, 3) ); // bc : returns the sequence number from position 1 To the position number 2(end before 1 A position ) The substring
console.log( s.slice(-3) ); // efg : returns from last to last 3 All characters from the beginning to the end
console.log( s.slice(-3, -1) ); // ef : returns from last to last 3 From the beginning to the end 2 a (end before 1 A position ) All characters of

4.11 split(delimiter, |arrayLength) : cuts the string into an array of strings by some kind of separator and returns it
Parameters:

delimiter {regexp | string} : the specified delimiter, which can be a regular expression or a string.

arrayLength {int} optional: split the length of the array. If omitted, returns all split substrings.

Note:

If the separator is in the first or last string, an empty string is added to the returned array.

The return value:

{string[]} returns an array of strings.

Example:


console.log( 'a,b,c,d,e'.split(',') ); // => ["a", "b", "c", "d", "e"]
console.log( ',a,b,c,d,e,'.split(',') ); // => ["", "a", "b", "c", "d", "e", ""] : the delimiter is added first or last 1 Empty strings
console.log( 'a,b,c,d,e'.split(',',3) ); // => ["a", "b", "c"] Returns the former 3 It's a divided substring
console.log( 'a1b2c3d4e'.split(/\d/) ); // => ["a", "b", "c", "d", "e"] : use a number as a separator

4.12 substr(start, |wordLength) : returns a substring of length from the start position to wordLength
Parameters:

start {int} : index of the starting position of the substring extraction (including the characters of this position).

If the number is negative, it starts at the end of the string. For example, -1 means the reciprocal of a string, and -2 means the reciprocal of the second character.

wordLength {int} optional: extract the length of the character. If this parameter is omitted, all characters from the start position to the end are returned.

The return value:

{string} returns the extracted string

Example:


ar s = 'abcdefg';
onsole.log( s.substr(0) ); // =>  abcdefg : omit the first 2 Returns the sequence number from the position 0 To start, 1 All the way to the last character
onsole.log( s.substr(0, 3) ); // => abc : returns the sequence number from position 0 Start, count 3 A character
onsole.log( s.substr(2, 4) ); // => cdef : returns the sequence number from position 2 Start, count 4 A character
onsole.log( s.substr(-2, 3) ); // fg : returns from last to last 2 Start with 1 string, count 3 a ( Beyond the character length, only characters that can be counted are returned )

4.13 substring(start, |end) : returns a substring from the start position to the first position of end
Parameters:

start {int} : index of the starting position of the substring extraction (including the characters of this position). The number cannot be negative, if it is negative, it is treated as 0

end {int} optional: index of the end position extracted from the substring (excluding the characters of this position). The number cannot be negative, if it is negative, it is treated as 0

The return value:

{string} returns a substring from the start position to the first position of end.

Example:


var s = 'abcdefg';
console.log( s.substring(0) ); // =>  abcdefg : omit end Parameter that returns the sequence number from the position 0 To start, 1 All the way to the last character
console.log( s.substring(0, 3) ); // => abc : returns the sequence number from position 0 Start to position number 2( (2) before the refs 1 a ) The character of
console.log( s.substring(2, 4) ); // => cd : returns the sequence number from position 2 Start to position number 3( (2) before the refs 1 a ) The character of
console.log( s.substring(-3, 3) ); // abc : if the parameter is negative, press the number 0 So this parameter actually returns the position sequence number 0 To the position number 3 The character of

4.14 toUpperCase() : converts the string to uppercase and returns
4.15 toUpperCase() : converts the string to lowercase and returns
trim() : removes the white space characters at the beginning and end of the string and returns them

That's all for this article. I hope you can have a new understanding of String objects in javascript.


Related articles: