1. Obtain the string length
Strings in JavaScript have a length attribute, which can be used to get the length of the string:
const str = 'hello'; Str.length // Output: 5 Copy codeCopy the code
2. Get the value at the specified position in the string
Both the charAt() and charCodeAt() methods can be indexed to get a value at a given location:
- The charAt() method retrieves the character at the specified position;
- The charCodeAt() method gets the Unicode value for the character at the specified position.
(1) the charAt ()
The charAt() method returns a character at a specified position. The syntax is as follows:
String. charAt(index) Copy codeCopy the code
Index indicates the index value of a character in a string:
const str = 'hello'; Str.charat (1) // Output: e copies the codeCopy the code
We know that strings can also be indexed to get characters directly, so what’s the difference between this and charAt()? Here’s an example:
const str = 'hello'; STR. CharAt (1) // Output result: e STR [1] // Output result: e STR. CharAt (5) // Output result: 'STR [5] // Output result: undefined copy codeCopy the code
As you can see, STR [index] returns undefined and charAt(index) returns an empty string if index is not in the length range of STR. In addition, STR [index] is not compatible with IE6-IE8, and charAt(index) is compatible.
(2) the charCodeAt ()
CharCodeAt () : This method returns the Unicode value of the character at the specified index position, an integer between 0 and 65535, representing the UTF-16 code unit at the given index, or NaN if there are no characters at the specified position:
let str = "abcdefg"; console.log(str.charCodeAt(1)); // "b" --> 98 Copy codeCopy the code
This method allows you to get characters in a string that specify a range of Unicode encoding values. For example, the Unicode encoding range for the numbers 0 to 9 is 48 to 57. This method can be used to filter the numbers in a string, although it is more convenient if you are more familiar with regular expressions.
3. Retrieve whether the string contains a particular sequence
All five methods can be used to retrieve whether a particular sequence is contained in a string. The first two methods get the index value of the specified element and only return the position of the first matched value. The last three methods return Boolean values indicating whether the specified value is matched.
Note: All 5 methods are case sensitive!
(1) the indexOf ()
IndexOf () : Searches for a character, if any, returns the position matched for the first time, otherwise returns -1.
String.indexof (searchValue,fromindex) copies the codeCopy the code
This method takes two parameters:
- Searchvalue: Required, specifying the string value to retrieve;
- Fromindex: An optional integer parameter specifying where to start retrieval in a string. Its legal values are 0 to String.length-1. If omitted, it is retrieved from the first character of the string.
let str = "abcdefgabc"; console.log(str.indexOf("a")); 0 console.log(str.indexof ("z")); 1 console.log(str.indexof ("c", 4)Copy the code
(2) the lastIndexOf ()
LastIndexOf () : Searches for a character, returns the position of the last match if any, and -1 otherwise
let str = "abcabc"; console.log(str.lastIndexOf("a")); 3 console.log(str.lastindexof ("z")); // Output: -1 copies the codeCopy the code
This method is similar to indexOf() except that the order of the lookup is different, indexOf() is a positive lookup and lastIndexOf() is a reverse lookup.
(3) includes ()
Includes () : This method is used to determine whether a string contains a specified substring. Returns true if a matching string is found, false otherwise. The syntax for this method is as follows:
String.includes (searchvalue, start) Copies the codeCopy the code
This method takes two parameters:
- Searchvalue: required, string to find;
- Start: Optional, set the search to start at that location. Default is 0.
let str = 'Hello world! '; Str.includes ('o') // Output result: true str.includes('z') // Output result: false str.includes('e', 2) // Output result: false copy codeCopy the code
(4) the startsWith ()
StartsWith () : this method checks if the string startsWith the specified substring. Returns true if it begins with the specified substring, false otherwise. The syntax is the same as the includes() method above.
let str = 'Hello world! '; Str.startswith ('Hello') // True str.startswith ('Helle') // False str.startswith ('wo', 6) // True copies the codeCopy the code
(5) the endsWith ()
EndsWith () : this method is used to determine whether the current string endsWith a specified substring. Returns true if the substring passed is at the end of the search string, false otherwise. The syntax is as follows:
String.endswith (searchValue, length) Copies the codeCopy the code
This method takes two parameters:
- Searchvalue: Required, substring to search for;
- Length: Sets the length of the string. The default value is the original string length, string.length.
let str = 'Hello world! '; str.endsWith('! ') // True str.endswith ('llo') // False str.endswith ('llo', 5) // True copy codeCopy the code
As you can see, when the second argument is set to 5, it is retrieved from the first five characters of the string, so it returns true.
4. Concatenate multiple strings
The concat() method is used to join two or more strings. This method does not alter the original string, but returns a new string that concatenates two or more strings. The syntax is as follows:
string.concat(string1, string2, ... , stringX) copies the codeCopy the code
Where parameters string1, string2… StringX is required, they will be concatenated into a string of one or more string objects.
let str = "abc"; console.log(str.concat("efg")); // Output: "abcefg" console.log(str.concat("efg","hijk")); // Output: "abcefghijk" copies the codeCopy the code
Although the concat() method is specifically used to concatenate strings, the addition operator + is used most often in development because it is simpler.
5. Split strings into arrays
The split() method splits a string into an array of strings. This method does not change the original string. The syntax is as follows:
String.split (separator,limit) Copies the codeCopy the code
This method takes two parameters:
- Separator: required. A string or regular expression that splits the string from the point specified by this parameter.
- Limit: Optional. This parameter specifies the maximum length of the array to be returned. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split regardless of its length.
let str = "abcdef"; str.split("c"); / / output: [" ab ", "def"] STR. The split (" ", 4) / / output: [' a ', 'b', 'c', 'd'] duplicate codeCopy the code
If an empty string is used as separator, each character in the string is separated.
str.split(""); ["a", "b", "c", "d", "e", "f"] copies the codeCopy the code
When splitting a string into an array, you can split multiple separators at the same time using regular expressions:
const list = "apples,bananas; cherries" const fruits = list.split(/[,;] /) console.log(fruits); ["apples", "bananas", "cherries"Copy the code
6. Intercept strings
The substr(), substring(), and slice() methods can all be used to intercept strings.
(1) the slice ()
The slice() method is used to extract a portion of a string and return the extracted portion in a new string. The syntax is as follows:
String. slice(start,end) copies codeCopy the code
This method takes two parameters:
- Start: Mandatory. The starting subscript of the segment to be cut, with the first character position 0. If it is negative, it is truncated from the tail.
- End: Optional. The subscript at the end of the clip to be captured. If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If the argument is negative, it specifies the position from the end of the string.
If start is negative, this parameter specifies the position from the end of the string. That is, -1 is the last character of the string, -2 is the second-to-last character, and so on:
let str = "abcdefg"; STR. Slice (1, 6); "Bcdef" str.slice(1); // Output: "bcdefg" str.slice(); // Output result: "abcdefg" str.slice(-2); // Output: "fg" str.slice(6, 1); // Output: "" Copy the codeCopy the code
Note that the substring returned by this method includes the character at the beginning but not the character at the end.
(2) the substr ()
The substr() method is used to extract a specified number of characters from the beginning subscript in a string. The syntax is as follows:
String. substr(start,length) copies codeCopy the code
This method takes two parameters:
- Start a necessity. The starting index of the substring to extract. It has to be a number. If it is negative, the argument declares the position from the end of the string. That is, -1 is the last character in the string, -2 is the second-to-last character, and so on.
- Length: Optional. Number of characters in a substring. It has to be a number. If this parameter is omitted, the string from the beginning of stringObject to the end is returned.
let str = "abcdefg"; STR. Substr (1, 6); // Output result: "bcdefg" str.substr(1); "Bcdefg" is equivalent to intercepting [1,str.length-1] str.substr(); // "abcdefg" is equivalent to intercepting [0,str.length-1] str.substr(-1); // Output: "g" copies the codeCopy the code
(3) the substring ()
The substring() method is used to extract the character of a string intermediate between two specified subscripts. The syntax is as follows:
String. substring(from, to) Copies codeCopy the code
This method takes two parameters:
- From: necessary. A non-negative integer specifying the position in the string of the first character of the substring to be extracted.
- To: Optional. A non-negative integer one more than the position in the string of the last character of the substring to be extracted. If omitted, the substring is returned up to the end of the string.
Note: If the arguments from and to are equal, this method returns an empty string (that is, a string of length 0). If from is larger than to, the method swaps these two arguments before extracting the substring. And the method does not accept negative arguments; if the argument is negative, the string is returned.
let str = "abcdefg"; STR. The substring (1, 6); // Output result: "bcdef" [1,6) str.substring(1); // Output result: "bcdef" [1,str.length-1] str.substring(); // Output result: "bcdef" [1,str.length-1] str.substring(); // Output result: "bcdef" [1,str.length-1] str.substring(); "Abcdefg" [0,str.length-1] str.substring(6,1); // output result "bcdef" [1,6) str.substring(-1); // output result: "abcdefg" replicates the codeCopy the code
Note that the substring returned by this method includes the character at the beginning but not the character at the end.
7. String case conversion
The toLowerCase() and toUpperCase() methods can be used to convert the case of a string.
(1) toLowerCase ()
ToLowerCase () : this method is used to convert a string toLowerCase.
let str = "adABDndj"; str.toLowerCase(); // Output: "adabdndj" copy codeCopy the code
(2) the toUpperCase ()
ToUpperCase () : this method is used to convert a string toUpperCase.
let str = "adABDndj"; str.toUpperCase(); // Output: "ADABDNDJ" copy codeCopy the code
We can use this method to uppercase the first character in a string:
Let word = 'apple' word = word[0].touppercase () + word.substr(1) console.log(wordCopy the code
8. String pattern matching
The replace(), match(), and search() methods can be used to match or replace characters.
(1) the replace ()
Replace () : This method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression. The syntax is as follows:
String.replace (searchValue, newValue) copies the codeCopy the code
This method takes two parameters:
- Searchvalue: Required. RegExp object that specifies the substring or schema to replace. If the value is a string, it is treated as a direct quantitative text pattern to retrieve, rather than being converted to a RegExp object first.
- Newvalue: required. A string value. Specifies a function that replaces text or generates replacement text.
let str = "abcdef"; Str.replace ("c", "z") // Output: abzdef copies the codeCopy the code
Perform a global substitution, ignoring case:
let str="Mr Blue has a blue house and a blue car"; str.replace(/blue/gi, "red"); 'Mr Red has a red house and a red car' copies the codeCopy the code
Note: If regexp has the global flag G, the replace() method replaces all matching substrings. Otherwise, it replaces only the first matching substring.
(2) the match ()
Match () : This method is used to retrieve a specified value within a string, or to find a match for one or more regular expressions. This method is similar to indexOf() and lastIndexOf(), but it returns the specified value rather than the position of the string. The syntax is as follows:
String.match (regexp) copies the codeCopy the code
The method argument regexp is required, specifying the regEXP object of the pattern to match. If the parameter is not a RegExp object, you need to first pass it to the RegExp constructor to convert it to a RegExp object.
Note: This method returns an array of matching results. The contents of the array depend on whether regexp has the global flag G.
let str = "abcdef"; Console. log(str.match("c")) // ["c", index: 2, input: "abcdef", groups: undefined] Copies the codeCopy the code
(3) the search ()
The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. The syntax is as follows:
String. search(searchValue) Copies codeCopy the code
The parameter regex to this method can be either a substring to retrieve in a string, or a RegExp object to retrieve.
Note: To perform a case-insensitive retrieval, append the flag I. This method does not perform a global match; it ignores the flag G, which returns only the first successful match. If no matching substring is found, -1 is returned.
Return value: Returns the starting position of the first substring in STR that matches regexp.
let str = "abcdef"; Str.search (/ BCD /) //Copy the code
9. Remove end-of-string whitespace
Trim (), trimStart(), and trimEnd() can be used to remove whitespace at the beginning and end of a string. Whitespace includes Spaces, tabs, newlines, and other whitespace.
(1) the trim ()
The trim() method removes whitespace at the beginning and end of a string without changing the original string:
Let STR = "abcdef" str.trim() // "abcdef" copies the codeCopy the code
Note that this method does not apply to null, undefined, or Number types.
(2) trimStart ()
The trimStart() method behaves like trim(), but returns a new string with whitespace removed from the beginning of the original string, without modifying the original string:
const s = ' abc '; S.trimstart () // "ABC" copies the codeCopy the code
(3) trimEnd ()
The trimEnd() method behaves like trim(), but returns a new string with whitespace removed from the end of the original string, without modifying the original string:
const s = ' abc '; S.trimend () // "ABC" copies the codeCopy the code
10. Get the string itself
The valueOf() and toString() methods both return the valueOf the string itself and feel useless.
(1) the valueOf ()
ValueOf () : returns the original valueOf a string object, which is usually called automatically by JavaScript rather than explicitly in code.
Let STR = "abcdef" console.log(str.valueof ()) // "abcdef" copies the codeCopy the code
(2) the toString ()
ToString () : Returns the string object itself
Let STR = "abcdef" console.log(str.tostring ()) // "abcdef" copies the codeCopy the code
11. Repeat a string
The repeat() method returns a new string, repeating the original string n times:
'x'.repeat(3) // Output result: "XXX" 'hello'. Repeat (2) // Output result: "helloHello" 'na'. Repeat (0) // Output result: "" Duplicate codeCopy the code
If the argument is a decimal, round down:
'na'.repeat(2.9) // Output: "nana" duplicates the codeCopy the code
Error if argument is negative or Infinity:
'na'. Repeat (Infinity) // RangeError 'na'. Repeat (-1) // RangeError copies the codeCopy the code
If the argument is a decimal between 0 and -1, it is equal to 0, because the round is performed first. If the decimal number between 0 and -1 is rounded to -0, repeat is regarded as 0.
'na'. Repeat (-0.9) // Prints the result: "" Copy the codeCopy the code
If the argument is NaN, this equals 0:
'na'. Repeat (NaN) // Prints the result: "" Copies the codeCopy the code
If the argument of the repeat is a string, it is converted to a number first.
'na'. Repeat (' na ') / / output: "" 'na'. Repeat (' 3 ') / / output:" nanana copying code"Copy the code
12. Complete the string length
The padStart() and padEnd() methods complement the length of the string. If a string is not of a specified length, the header or tail is completed.
(1) padStart ()
PadStart () is used for head completion. The method takes two arguments, the first of which is a number representing the length of the string after completion. The second argument is the string used for completion.
If the length of the original string is equal to or greater than the specified minimum length, the original string is returned:
'x'.padstart (1, 'ab') // 'x' copies codeCopy the code
If the sum of the length of the completion string and the original string exceeds the specified minimum length, the completion string exceeding the number of bits is truncated:
'x'. PadStart (5, 'ab') / / 'ababx' 'x'. The padStart (4, 'ab') / / 'abax duplicate codeCopy the code
If the second argument is omitted, the default space is used to complete the length:
'x'.padstart (4) // 'x' copies the codeCopy the code
A common use of padStart() is to specify the number of digits for numeric completion. A recent requirement of the author was to complete the number of pages returned by three digits, such as 001 on page 1, using this method:
"1". PadStart (3 '0') / / output results: '001' "15" padStart (3 '0') / / output results: '015' copying codeCopy the code
(2) padEnd ()
PadEnd () is used for tail completion. This method also takes two parameters, the first parameter is the maximum length that string completion takes effect, and the second parameter is the string used for completion:
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
Copy the code