Table of contents
2.The length attribute returns the length of the string. This attribute cannot be changed.
ES6 new string instance method
4.repeat() returns a new string, which means repeating the original string n times.
Understanding of strings
1. A string can be regarded as a character array, so you can use the square bracket operator of the array to return the character at a certain position (the position number starts from 0)
<script>
var s = 'hello';
console.log(s[0]); // "h"
console.log(s[1]); // "e"
console.log(s[4]); // "o"
// 直接对字符串使用方括号运算符
console.log('hello'[1]); // "e"
</script>
Note: If the number in the square brackets exceeds the length of the string, or if the number in the square brackets is not a number at all, it will be returned undefined
.
<script>
console.log('abc'[3]); // undefined
console.log('abc'[-1]); // undefined
console.log('abc'['x']); // undefined
</script>
Note: The similarity between strings and arrays ends there. In fact, you cannot change individual characters within a string.
<script>
var str = 'hello';
var arr = [0,1,2,3,4];
//删除
delete str[0];
console.log(str); // "hello"
delete arr[0];
console.log(arr);//[empty, 1, 2, 3, 4]
//替换
str[1] = 'a';
console.log(str);// "hello"
arr[1] = 'a';
console.log(arr);// [empty, 'a', 2, 3, 4]
//增加
str[5] = '!';
console.log(str);//"hello"
arr[5] = '!';
console.log(arr);//[empty, 'a', 2, 3, 4, '!']
</script>
Analysis: Single characters within the string cannot be changed, added or deleted, and these operations will fail.
2.The length attribute returns the length of the string, and this attribute cannot be changed.
<script>
var s = 'hello';
console.log(s.length); // 5
s.length = 3;
console.log(s.length);// 5
s.length = 7;
console.log(s.length);// 5
</script>
String overview
String is an official built-in function used to generate string objects.
<script>
var s1 = 'abc';
var s2 = new String('abc');
console.log(typeof s1); // "string"
console.log(typeof s2); // "object"
console.log(s2.valueOf()); // "abc"
</script>
Analysis: In the above code, the variables s1
are strings and s2
objects . Since s2
it is a string object , s2.valueOf
the method returns the original string corresponding to it .
Note: A string object is an array-like object (much like an array, but not an array).
<script>
console.log(new String('abc'));
// String {0: "a", 1: "b", 2: "c", length: 3}
console.log((new String('abc'))[1]); // "b"
</script>
Analysis: In the above code, the abc
string object corresponding to the string has numeric keys ( 0
, 1
, 2
) and length
attributes , so it can take values like an array .
Note: In addition to being used as a constructor, String
objects can also be used as utility methods to convert any type of value into a string.
<script>
console.log(String(true)); // "true"
console.log(String(5) );// "5"
</script>
String methods
1.charAt() returns the character at the specified position, and the parameter is 0
the position numbered from the beginning.
<script>
var s = new String('abc');
console.log(s);//String {0: "a", 1: "b", 2: "c", length: 3}
s.charAt(1) // "b"
s.charAt(s.length - 1) // "c"
</script>
This method can be completely replaced by array subscripts:
<script>
'abc'.charAt(1) // "b"
'abc'[1] // "b"
</script>
Note: If the parameter is a negative number, or is greater than or equal to the length of the string, charAt
an empty string is returned.
<script>
console.log('abc'.charAt(-1)); // ""
console.log('abc'.charAt(3)); // ""
</script>
2.charCodeAt() returns the Unicode value of the character at the specified index position (decimal representation)
<script>
console.log('abc'.charCodeAt(1)); // 98
</script>
Analysis: In the above code, the character at abc
the 1
number position is b
, and its Unicode code point is 98
.
Note: If there are no parameters, charCodeAt
the Unicode code point of the first character is returned .
<script>
console.log('abc'.charCodeAt());// 97
</script>
Note: If the parameter is a negative number , or is greater than or equal to the length of the string, charCodeAt
it is returned NaN
. (charAt returns an empty string)
<script>
console.log('abc'.charCodeAt(-1)); // NaN
console.log('abc'.charCodeAt(4));// NaN
</script>
3.concat() is used to connect two strings and return a new string without changing the original string.
<script>
var s1 = 'abc';
var s2 = 'def';
var re = s1.concat(s2);
console.log(re);// "abcdef"
console.log(s1); // "abc"
</script>
Note: This method can accept multiple parameters .
<script>
console.log('a'.concat('b', 'cd')); // "abcd"
</script>
Note: If the parameter is not a string, concat
the method will convert it to a string first and then concatenate it .
<script>
var one = 1;
var two = true;
var three = '3';
var re = ''.concat(one, two, three);
console.log(re); // '1true3'
console.log(one + two + three); // "23"
</script>
Analysis: In the above code, concat
the method converts the parameters into strings first and then connects them, so a three-character string is returned . In contrast , the plus operator does not convert types when both operands are numeric, so a two-character string is returned. (1+true=>1+1=2 2+'3'=>'2'+'3' ='23' You don't just convert everything into a string when you see '3')
4. slice() is used to remove a substring from the original string and return it without changing the original string. Its first parameter is the starting position of the substring, and the second parameter is the ending position of the substring (excluding this position). (The second parameter can be omitted)
<script>
var re = 'JavaScript'.slice(0, 4);
console.log(re);// "Java" 返回结果是一个字符串
</script>
Note: If the parameter is a negative value , it indicates the countdown position from the end, that is, the negative value plus the length of the string. It means that when the parameter is a negative number, count down from the end (counting starts from 1, not from 0) .
<script>
console.log('JavaScript'.slice(-6)); // "Script"
//一个参数是子字符串的开始位置,第二个参数是子字符串的结束位置(不含该位置)。
console.log('JavaScript'.slice(0, -6)); // "Java"
console.log('JavaScript'.slice(-2, -1)); // "p"
</script>
Note: If the first parameter is greater than the second parameter, slice
the method returns an empty string .
<script>
console.log('JavaScript'.slice(2, 1)); // ""
</script>
Special case:
//一个参数是子字符串的开始位置,第二个参数是子字符串的结束位置(不含该位置)。
console.log('JavaScript'.slice(0, -6)); // "Java"
5.substring() is used to remove the substring from the original string and return it without changing the original string . It slice
is very similar to the method. Its first parameter represents the starting position of the substring , and the second position represents the ending position (the return result does not include this position) .
<script>
console.log('JavaScript'.substring(0, 4)); // "Java"
</script>
Note: If the second parameter is omitted, it means that the substring reaches the end of the original string.
<script>
console.log('JavaScript'.substring(4)) // "Script"
</script>
Note: If the first parameter is greater than the second parameter, substring
the method will automatically replace the positions of the two parameters .
<script>
console.log('JavaScript'.substring(10, 4)); // "Script"
// 等同于
console.log('JavaScript'.substring(4, 10)); // "Script"
</script>
Analysis: In the above code, the two parameters of the method are exchanged substring
, and the same result is obtained .
Note: If the parameter is a negative number, substring
the method will automatically convert the negative number to 0 .
<script>
console.log('Javascript'.substring(-3)); // "JavaScript"
console.log('Javascript'.substring(0)); // "JavaScript"
console.log('JavaScript'.substring(4, -3)); // "Java"
console.log('JavaScript'.substring(4, 0)); // "Java"
console.log('JavaScript'.substring(0, 4)); // "Java"
</script>
Analysis: In the above code, the parameters-3
0
'JavaScript'.substring(4, 0)
of the second example will automatically become equal to . Since the second parameter is smaller than the first parameter, the positions will be automatically swapped, so it is returnedJava
.
Summary: Since these rules are counterintuitive, substring
methods are not recommended and should be used in preferenceslice
6.
substr() is used to extract a substring from the original string and return it without changing the original string. substr
The first parameter of the method is the starting position of the substring (calculated from 0), and the second parameter is the substring. length
<script>
console.log('JavaScript'.substr(4, 6)) // "Script"
</script>
Note: If the second parameter is omitted, it means that the substring reaches the end of the original string.
<script>
console.log('JavaScript'.substr(4)) // "Script"
</script>
Note: If the first parameter is a negative number , it indicates the character position of the reciprocal calculation . It means that when the parameter is a negative number, count down from the end (counting starts from 1, not from 0). If the second parameter is a negative number, it will be automatically converted to 0, so an empty string will be returned.
<script>
console.log('JavaScript'.substr(-6));// "Script"
//第二个参数是子字符串的长度
console.log('JavaScript'.substr(4, -1)); // ""
console.log('JavaScript'.substr(4, 0)); // ""
</script>
Analysis: In the above code, the parameter of the second example -1
is automatically converted to 0
, indicating that the length of the substring is 0
, so an empty string is returned.
7. indexOf() is used to determine the position where a string first appears in another string. The return result is the position where the match starts. If returned -1
, it means there is no match.
<script>
console.log('hello world'.indexOf('o')); // 4
console.log('JavaScript'.indexOf('script')); // -1
</script>
Note: indexOf
The method can also accept a second parameter, which means matching backwards from this position.
<script>
//第一个参数为 一个字符串在另一个字符串中第一次出现的位置
//第二个参数,表示从该位置开始向后匹配,匹配到后(但是算的时候是从0开始算的)
console.log('hello world'.indexOf('o', 6)); // 7
</script>
8.lastIndexOf() is the first occurrence position encountered from the tail. The return result of this position is calculated from the left, not from the right.
<script>
console.log('hello world'.lastIndexOf('o')); // 7
</script>
Note: lastIndexOf
The second parameter indicates matching forward from this position.
<script>
console.log('hello world'.lastIndexOf('o', 6)); // 4
</script>
Analysis: When matching, match forward from this position, and the return value is calculated from left to right.
9.trim() is used to remove spaces at both ends of a string and return a new string without changing the original string. This method removes not only spaces, but also tab characters ( \t
, \v
), line feed characters ( \n
) and carriage return characters ( \r
)
<script>
var str = ' hello world ';
var re = str.trim();
console.log(re);
// "hello world"
var str1 = '\r\nabc \t';
console.log(str1.trim()); // 'abc'
</script>
10.toLowerCase() is used to convert all strings to lowercase and return a new string without changing the original string.
<script>
var str = 'Hello World';
var re = str.toLowerCase()
console.log(re);// "hello world"
</script>
11.toUpperCase() Converts a string to all uppercase letters and returns a new string without changing the original string.
<script>
var str = 'Hello World';
var re = str.toUpperCase()
console.log(re);// "HELLO WORLD"
</script>
12.match() is used to determine whether the original string matches a certain substring and returns an array whose members are the first matched string. If no match is found, returnnull
<script>
var str = 'cat, bat, sat, fat';
var re1 = str.match('at') // ["at"]
console.log(re1);
var re2 = str.match('xt') // null
console.log(re2);
</script>
Analysis: The returned array also has index
attributes and input
properties , which represent the starting position of the matched string and the original string respectively .
Note: match
Methods can also use regular expressions as parameters .
13. The usage of the search() method is basically the same match
, but the return value is the first position of the match. Returns if no match is found -1
.
<script>
var re = 'cat, bat, sat, fat'.search('at')
console.log(re);//1
</script>
Note: search
Methods can also take regular expressions as parameters.
14.replace() is used to replace matching substrings. Generally, only the first match is replaced (unless a regular g
expression with modifiers is used).
<script>
var re = 'aaa'.replace('a', 'b');
console.log(re);// "baa"
</script>
NOTE: replace
Methods can also take regular expressions as parameters
15. split() splits the string according to the given rules and returns an array composed of the split substrings
<script>
var re = 'a|b|c'.split('|');
var re1 = 'a|b|c'.split('a');
console.log(re);// ["a", "b", "c"]
console.log(re1);//['', '|b|c']
</script>
Note: If the splitting rule is an empty string, the members of the returned array are each character of the original string.
<script>
console.log('a|b|c'.split('')); // ['a', '|', 'b', '|', 'c']
</script>
Note: If the parameter is omitted, the only member of the returned array is the original string .
<script>
var re = 'a|b|c'.split() // ["a|b|c"]
console.log(re);
</script>
Note: If the two parts that satisfy the splitting rules are immediately adjacent (that is, there are no other characters between the two delimiters), there will be an empty string in the returned array.
<script>
console.log('a||c'.split('|')); // ['a', '', 'c']
</script>
Note: If the part that satisfies the splitting rules is at the beginning or end of the string (that is, there are no other characters before or after it), the first or last member of the returned array is an empty string.
<script>
console.log('|b|c'.split('|')); // ["", "b", "c"]
console.log('a|b|'.split('|')); // ["a", "b", ""]
</script>
Note: split
The method can also accept a second parameter to limit the maximum number of members of the returned array.
<script>
console.log('a|b|c'.split('|', 0)); // []
console.log('a|b|c'.split('|', 1)); // ["a"]
console.log('a|b|c'.split('|', 2)); // ["a", "b"]
console.log('a|b|c'.split('|', 3)); // ["a", "b", "c"]
console.log('a|b|c'.split('|', 4)); // ["a", "b", "c"]
</script>
Analysis: split
The second parameter of the method determines the number of members of the returned array .
NOTE: split
Methods can also take regular expressions as parameters
ES6 new string instance method
1.includes() can be used to determine whether a string is included in another string and returns a Boolean value indicating whether the parameter string is found.
<script>
let s = 'Hello world!';
var re = s.includes('o') // true
console.log(re);
</script>
2.startsWith() can be used to determine whether a string is contained in another string. It returns a Boolean value indicating whether the parameter string is at the head of the original string.
<script>
let s = 'Hello world!';
var re = s.startsWith('Hello');
var re1 = s.startsWith('llo');
console.log(re); //true
console.log(re1);//false
</script>
3.endsWith() can be used to determine whether a string is contained in another string and returns a Boolean value indicating whether the parameter string is at the end of the original string.
<script>
let s = 'Hello world!';
var re = s.endsWith('!') // true
var re1 = s.endsWith('ld!');//true
console.log(re);
console.log(re1);
</script>
Note: The above three methods all support the second parameter, which indicates the starting position of the search.
<script>
let s = 'Hello world!';
console.log(s.startsWith('world', 6)); // true
console.log(s.endsWith('Hello', 5)); // true
console.log(s.includes('Hello', 6)); // false
</script>
Analysis: The above code shows that when using the second parametern
, endsWith
the behavior is different from the other two methods . It targets the previous n
character (counting from n), while the other two methods target the character from the th n
position (counting from n) until the end of the string .
4.repeat() returns a new string, which means repeating the original string n
several times.
<script>
var re = 'x'.repeat(3);
console.log(re);// "xxx"
var re1 = 'hello'.repeat(2) // "hellohello"
console.log(re1);
var re2 = 'na'.repeat(0) // ""
console.log(re2);
</script>
Note: If the parameter is a decimal, it will be rounded.
<script>
console.log('na'.repeat(2.9)) // "nana"
console.log('na'.repeat(2.1)) // "nana"
</script>
Analysis: Round down. Math.floor()
Note: If repeat
the parameter is a negative number Infinity
, an error will be reported.
<script>
console.log('na'.repeat(Infinity));
// RangeError
console.log('na'.repeat(-1));
// RangeError
</script>
Note: If the parameter is a decimal between 0 and -1, it is equivalent to 0 because the rounding operation is performed first. -0
Decimals between 0 and -1 are equal to 0 after rounding repeat
.
<script>
console.log('na'.repeat(-0.9)); // ""
</script>
Note: The parameter NaN
is equal to 0.
<script>
console.log('na'.repeat(NaN)); // ""
console.log('na'.repeat(0)); // ""
</script>
Note: If repeat
the parameter is a string, it will be converted to a number first.
<script>
console.log('na'.repeat('na')); // ""
console.log('na'.repeat('3')); // "nanana"
</script>
Analysis: The string 'na' converted to a number is NaN. As we know earlier, the repeat method will treat the parameter NaN as 0. The string '3' is converted to the number 3.
5.padStart() and padEnd() If a string is not long enough, it will be completed at the head or tail. padStart()
Used for head completion and padEnd()
tail completion.
padStart()
and padEnd()
accepts a total of two parameters. The first parameter is the maximum length for string completion to take effect, and the second parameter is the string used for completion.
<script>
console.log('x'.padStart(5, 'ab')); // 'ababx'
console.log('x'.padStart(4, 'ab')); // 'abax'
console.log('x'.padEnd(5, 'ab')); // 'xabab'
console.log('x'.padEnd(4, 'ab')); // 'xaba'
</script>
Note: If the length of the original string is equal to or greater than the maximum length, string completion will not take effect and the original string will be returned.
<script>
var re = 'xxx'.padStart(2, 'ab') // 'xxx'
var re1 = 'xxx'.padEnd(2, 'ab') // 'xxx'
console.log(re);
console.log(re1);
</script>
Note: If the sum of the lengths of the string used for completion and the original string exceeds the maximum length, the completion string that exceeds the number of digits will be truncated.
<script>
console.log('abc'.padStart(10, '0123456789'));
// '0123456abc'
</script>
Note: If the second parameter is omitted, spaces will be used to complete the length by default.
<script>
console.log('x'.padStart(4)); // ' x'
console.log('x'.padEnd(4)); // 'x '
</script>
Note: padStart()
A common use for numeric completion is to specify the number of digits for numeric completion. The following code generates a 10-digit numerical string
'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"
Note: Another use is to prompt string format .
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
6. Their behavior is consistent with these two methods trimStart()
, eliminating spaces at the head of the string and eliminating spaces at the end. They return new strings and do not modify the original strings.trimEnd()
trim()
trimStart()
trimEnd()
<script>
const s = ' abc ';
console.log(s.trim()); // "abc"
console.log(s.trimStart()); // "abc "
console.log(s.trimEnd()); // " abc"
</script>
Analysis: In the above code, trimStart()
only the leading spaces are eliminated and the trailing spaces are retained . trimEnd()
Similar behavior. In addition to the space bar, these two methods are also effective for invisible white space symbols such as tab keys and line breaks at the head (or end) of the string. The browser also deploys two additional methods, trimLeft()
yes trimStart()
aliases and trimRight()
yes trimEnd()
aliases.