String String Object
1. Introduction
String object, operates on strings, such as: intercepting a substring, searching for strings/characters, converting upper and lower case, etc.
2. Definition method
2.1 new String(Value) constructor: Return a String object with Value content
parameter:
①value {String}: string
Return value:
{String object} Returns a String object with Value
Example:
The code copy is as follows:
var demoStr = new String('abc');
console.log(typeof demoStr); // => object
console.log(demoStr); // => abc
2.2 Direct assignment (recommended)
Example:
The code copy is as follows:
var demoStr = 'abc';
console.log(typeof demoStr); // string
console.log(demoStr); // => abc
3. Instance properties
3.1 length: Return the number of characters in the string
The code copy is as follows:
var s = 'abc';
console.log(s.length); // => 3
console.log('Happy New Year'.length); // => 4: One Chinese character is also calculated as 1 quantity
console.log(''.length); // => 0: Empty string returns 0
4. Example method
Note: The instance method of a string will not change the string itself, and will only return the result after the operation.
4.1 charAt(index): Returns the character at the specified position in a string, the number starts from 0. If a non-existent value is passed in, the empty string will be returned.
parameter:
①index {int}: position index, calculated from 0
Return value:
{string} Returns the character at the specified position in a string; if a value of a non-existent position is passed, it returns an empty string
Example:
The code copy is as follows:
var s = 'abc';
console.log(s.charAt(1)); // => b: Returns the character with position 1
console.log(s); // => does not affect the original array
console.log(s.charAt(5)); // => '': Get a character with no position and return an empty string of length 0
4.2 charCodeAt(index): Returns the Unicode encoding of the specified position character in a string
parameter:
①index {int}: position index, calculated from 0
Return value:
{number} Returns the Unicode encoding of the specified position character in a string; if a non-existent position value is passed, return NaN
Example:
The code copy is as follows:
var s = 'abc';
console.log(s.charCodeAt(0)); // => 98: Unicode encoding of character b
console.log(s.charCodeAt(5)); // => NaN: Get a character with no position and return NaN
4.3 concat(value1,value2 ... valueN): concatenate one or more strings and return the connected string
parameter:
①value1,value2 ... valueN {string}: One or more strings
Return value:
{string} Returns the connected string
Example:
The code copy is as follows:
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): Find a string or character from front to back in the instance and return the found position (counting from 0). If not found, return -1
parameter:
①value {string}: the string to be found
②startPosition {int} Optional: The starting position of the start search, the default search starts from position 0.
Return value:
{int} Returns the found position (counting from 0). If not found, return -1
Example:
The code copy is as follows:
var s = 'abc';
console.log(s.indexOf('b')); // => 1
console.log(s.indexOf('d')); // => -1: Not found
console.log(s.indexOf('b', 2)); // => -1: Start searching from position 2 (at the third character)
4.5 lastIndexOf(value, |startPosition): In the instance, find a string or character from behind to front, and return the found position (counting from 0). If not found, return -1
parameter:
①value {string}: the string to be found
②startPosition {int} Optional: The starting position of the start search, the default search starts from the last one
Return value:
{int} Returns the found position (counting from 0). If not found, return -1
Example:
The code copy is as follows:
var s = 'abcabc';
console.log(s.lastIndexOf('a')); // => 3: Search from behind to front
console.log(s.lastIndexOf('d')); // => -1: No found return -1
console.log(s.lastIndexOf('a', 2)); // => 0: Start looking forward from position 2 (at the third character)
4.6 localeCompare(value): Compare the instance with the parameters and return the comparison result
parameter:
①value {string}: string to be compared
Return value:
0: The instance is larger than the parameters
1: The instance and the parameters are equal
-1: The instance is smaller than the parameters
Example:
The code copy is as follows:
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 matching search
parameter:
①regexp {regexp}: regular expression, eg://d+/
Return value:
Different results are returned based on whether the regular expression has the attribute 'g'; if there is no match, return {null}:
① The regular expression does not have the attribute 'g', performs a match once, and returns the result object {single match}, which contains the following properties:
Array number: represents the matching result, 0 is the matching text, 1 is the matching result from the first parentheses to the right, 2 is the second parentheses, and so on
Index attribute: indicates that the matching text is at the beginning of the matching source
input attribute: indicates the matching source
② The regular expression has the attribute 'g', perform global matching, find all matching objects of the string, and return a {string array}: The array element contains each matching object in the string, does not contain the string in the regular expression bracket, and does not provide index and input attributes.
Example:
The code copy is as follows:
// 1. Single match
var s = 'a1b2c3d4';
var mc = s.match(//d+/); // => Get the result of the first 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: Match source
console.log(mc[0]); // => 1: Get the matching result
}
// 2. Global Match
var mcArray = s.match(//d+/g); // => Get all regular match 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 matching result
}
}
// 3. Match with brackets
s = 'a1b2c3d4';
mc = s.match(/[az]([1-9])/); // => Get the result of the first 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: Match source
console.log(mc[0]); // => a1: Serial number 0 indicates the matching result
console.log(mc[1]); // => 1: Serial number 1 represents the sub-match result in the first bracket
}
4.8 replace(regexp, replaceStr): replaces the substring matched by the regular expression and returns the replaced string
parameter:
①regexp {regexp}: regular expression. eg://d+/
②replaceStr {string | function}:
1) If it is a string, it means the replaced string, and the matching string is replaced with this string;
The $ character in a string has a special meaning:
$1,$2 ... $99: indicates the matching child of ① parameter from left to right brackets
$&: represents the child matching the entire parameter ①
$$: dollar sign
2) If it is a function, it means that this function is called for each matching result. The only parameter of the function is the matching result, and a replacement result is returned.
Return value:
{string} Returns a replaced string
Example:
The code copy is as follows:
var oldStr = 'a1b2c3d4';
// 1. Regularly match [all] numbers, replace with: ',' comma
var newStr = oldStr.replace(//d+/g, ',');
console.log(newStr); // => a,b,c,d,
// 2. Regularly match [all] numbers, replace with: match result + ',' comma
newStr = oldStr.replace(//d+/g, '$&,');
console.log(newStr); // => a1,b2,c3,d4,
// 3. Regularly match [all] numbers, each matching result calls the function, and return the replaced result
newStr = oldStr.replace(//d+/g, function (word) {
if (word % 2 == 0) {
return 'even';
}
return 'Yi';
});
console.log(newStr); // => a odd b even c odd d even
4.9 search(regexp): Returns the position where the first match of the regular expression is found
parameter:
①regexp {regexp}: regular expression. eg://d+/
Return value:
{int} Returns the position of the first matched result; if no matched result is found, return -1
Example:
The code copy is as follows:
console.log( 'abcd'.search(//d+/) ); // => -1 : No number found
console.log( 'abcd1234'.search(//d+/) ); // => 4: The position number is 4, returning the position of the first number
4.10 slice(start, |end): Returns the substring from the start position of the string to the previous position of the end
parameter:
① start {int}: The index of the start position of the substring extract (including the characters at this position).
If the number is negative, it means that the calculation starts from the end of the string. For example: -1 means the countdown string, and -2 means the countdown character.
②end {int} Optional: The end position index of the substring extracted (excluding characters at this position).
If the number is negative, it means that the calculation starts from the end of the string. For example: -1 means the countdown string, and -2 means the countdown character.
If this parameter is omitted, all characters from the start position to the end are returned.
Notice:
The order of extraction of substrings is from left to existence. If the start index position is greater than the end index position, an empty string will be returned.
Return value:
{string} Returns a substring from the start position of the string to the previous position of the end.
Example:
The code copy is as follows:
var s = 'abcdefg';
console.log( s.slice(1) ); // bcdefg: omit the end parameter, the end position is the end
console.log( s.slice(1, 3) ); // bc: Returns the substring from position number 1 to position number 2 (the previous position of end)
console.log( s.slice(-3) ); // efg: Returns all characters from the third to the end
console.log( s.slice(-3, -1) ); // ef: Returns all characters from the third to the second (the previous position of the end)
4.11 split(delimiter, |arrayLength): divides the string into an array composed of strings according to some separator and returns
parameter:
①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, return all divided substrings.
Notice:
If the delimiter is on the first or last string, an empty string will be added to the returned array.
Return value:
{ string[] } Returns an array of strings.
Example:
The code copy is as follows:
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 first or last, and an empty string will be added
console.log( 'a,b,c,d,e'.split(',',3) ); // => ["a", "b", "c"] : Return the first 3 split substrings
console.log( 'a1b2c3d4e'.split(//d/) ); // => ["a", "b", "c", "d", "e"] : Use numbers as separators
4.12 substr(start, |wordLength): Returns a substring that is calculated from the start position of the string to wordLength length
parameter:
① start {int}: The index of the start position of the substring extract (including the characters at this position).
If the number is negative, it means that the calculation starts from the end of the string. For example: -1 means the countdown string, and -2 means the countdown 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.
Return value:
{string} Returns the extracted string
Example:
The code copy is as follows:
ar s = 'abcdefg';
onsole.log( s.substr(0) ); // => abcdefg: omit the second parameter and return the character starting from position number 0 and up to the last one
onsole.log( s.substr(0, 3) ); // => abc: Returns starting from position number 0 and counting 3 characters
onsole.log( s.substr(2, 4) ); // => cdef: Returns starting from position number 2 and counting 4 characters
onsole.log( s.substr(-2, 3) ); // fg: Returns starting from the penultimate string and counting 3 (after exceeding the character length, only statisticable characters are returned)
4.13 substring(start, |end): Returns the substring from the start position of the string to the previous position of the end
parameter:
① start {int}: The index of the start position of the substring extract (including the characters at this position). The number cannot be a negative number. If it is a negative number, it is processed as 0.
②end {int} Optional: The end position index of the substring extracted (excluding characters at this position). The number cannot be a negative number. If it is a negative number, it is processed as 0.
Return value:
{string} Returns a substring from the start position of the string to the previous position of the end.
Example:
The code copy is as follows:
var s = 'abcdefg';
console.log( s.substring(0) ); // => abcdefg: omit the end parameter and return the character starting from position number 0 and up to the last one
console.log( s.substring(0, 3) ); // => abc: Returns the character starting from position number 0 to position number 2 (the previous one of the ② parameter)
console.log( s.substring(2, 4) ); // => cd: Returns the character starting from position number 2 to position number 3 (the previous one of the ② parameter)
console.log( s.substring(-3, 3) ); // abc: If the parameter is negative, it will be processed as the number 0, so this parameter actually returns the characters from position number 0 to position number 3
4.14 toUpperCase(): Convert the string to uppercase and return
4.15 toUpperCase(): Convert string to lowercase and return
4.16 trim(): Remove the whitespace characters at the beginning and end of the string and return
The above is all about this article. I hope that through this article, you will have a new understanding of String objects in JavaScript.