Commonly used string methods and usage skills

1. Get the string length

Strings in JavaScript have a length property, which can be used to get the length of the string;

const str = 'hello';
str.length  // 输出结果:5

2. Get the value at the specified position of the string

Both charAt() and charCodeAt() methods can get the value at the specified position through the index:

  • The charAt() method gets the character at the specified position;
  • The charCodeAt() method gets the Unicode value of the character at the specified position.

1、charAt()

The charAt() method returns the character at the specified position. Its syntax is as follows:

string.charAt(index)

index indicates the index value of the character in the string;

const str = 'hello';
str.charAt(1)  // 输出结果:e 

We know that a string can also directly obtain the corresponding character through the index value, so what is the difference between it and charAt()? Let's see an example:

const str = 'hello';
str.charAt(1)  // 输出结果:e 
str[1]         // 输出结果:e 
str.charAt(5)  // 输出结果:'' 
str[5]         // 输出结果:undefined

It can be seen that when the value of index is not within the length range of str, str[index] will return undefined, and charAt(index) will return an empty string; in addition, str[index] is not compatible with ie6-ie8 , charAt(index) is compatible

2、charCodeAt()

charCodeAt(): This method returns the Unicode value of the character at the specified index position. The return value is an integer between 0 and 65535, representing the UTF-16 code unit at the given index. If there is no character at the specified position, NaN will be returned :

let str = "abcdefg";
console.log(str.charCodeAt(1)); // "b" --> 98

Through this method, you can get the characters in the specified range of Unicode encoding values ​​in the string. For example, the Unicode encoding range of the numbers 0~9 is: 48~57, you can use this method to filter the numbers in the string, of course, if you are more familiar with regular expressions, it will be more convenient.

3. Retrieve whether the string contains a specific sequence

These five methods can be used to retrieve whether a string contains a specific sequence. Among them, 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: These 5 methods are all case sensitive!

1、indexOf()

indexOf(): Find a certain character, if there is one, return the first matching position , otherwise return -1, its syntax is as follows:

string.indexOf(searchvalue,fromindex)

This method has two parameters:

  • searchvalue: required, specifies the string value to be retrieved;
  • fromindex: An optional integer parameter specifying the position in the string to start searching. Its valid values ​​are 0 to string.length - 1. If this is omitted, the search starts 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)) // 输出结果:9

2、lastIndexOf()

lastIndexOf(): Find a character, return the last matched position if there is one, otherwise return -1

let str = "abcabc";
console.log(str.lastIndexOf("a"));  // 输出结果:3
console.log(str.lastIndexOf("z"));  // 输出结果:-1

This method is similar to indexOf(), except that the order of searching is different. indexOf() is searching in positive order, and lastIndexOf() is searching in reverse order.

3、includes()

includes(): This method is used to determine whether the string contains the specified substring. Returns true if a matching string is found, false otherwise. The syntax of the method is as follows:

string.includes(searchvalue, start)

This method has two parameters:

  • searchvalue: required, the string to be searched;
  • start: optional, set the location from which to start searching, the default is 0.

let str = 'Hello world!';

str.includes('o')  // 输出结果:true
str.includes('z')  // 输出结果:false
str.includes('e', 2)  // 输出结果:false

4、startsWith()

startsWith(): This method is used to detect whether the string starts with the specified substring . Returns true if it starts with the specified substring, otherwise false. Its 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

5、endsWith()

endsWith(): This method is used to determine whether the current string ends with the specified substring . Returns true if the passed in substring is at the end of the search string, false otherwise. Its syntax is as follows:

string.endsWith(searchvalue, length)

This method has two parameters:

  • searchvalue: required, the substring to search for;
  • length: Set 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

It can be seen that when the second parameter is set to 5, it will be retrieved from the first 5 characters of the string, so it will return true

Fourth, concatenate multiple strings

The concat() method is used to concatenate two or more strings. This method does not change the original string, but returns a new string that concatenates two or more strings. Its syntax is as follows:

string.concat(string1, string2, ..., stringX)

Among them, the parameters string1, string2, ..., stringX are required, and they will be concatenated as one or more string objects of a string.

let str = "abc";
console.log(str.concat("efg"));          //输出结果:"abcefg"
console.log(str.concat("efg","hijk")); //输出结果:"abcefghijk"

Although the concat() method is specially used to concatenate strings, the plus operator + is most used in development because it is simpler.

Five, split the string into an array

The split() method is used to split a string into an array of strings. This method does not alter the original string. Its syntax is as follows:

string.split(separator,limit)

This method has two parameters:

  • separator: Required. String or regular expression, split string from where specified by this parameter.
  • limit: optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings will be returned than the array specified by this parameter. If this parameter is not set, the entire string will be split regardless of its length.

let str = "abcdef";
str.split("c");    // 输出结果:["ab", "def"]
str.split("", 4)   // 输出结果:['a', 'b', 'c', 'd'] 

If an empty string is used as separator, each character in the string will be split.

str.split("");     // 输出结果:["a", "b", "c", "d", "e", "f"]

In fact, when splitting a string into an array, multiple separators can be split at the same time, which can be achieved by using regular expressions:

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits);  // 输出结果:["apples", "bananas", "cherries"]

Six, intercept the string

substr (), substring () and slice () method can be used to intercept the string.

1、slice()

The slice() method is used to extract a part of a string and return the extracted part as a new string. Its syntax is as follows:

string.slice(start,end)

This method has two parameters:

  • start: required. The starting subscript of the segment to be intercepted, the first character position is 0. If negative, intercept from the end.
  • end: optional. The subscript of the end of the segment to be intercepted. If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If this parameter is negative, it specifies the position from the end of the string.

As mentioned above, if start is a negative number, this parameter specifies the position from the end of the string. That is, -1 refers to the last character of the string, -2 refers to the second-to-last character, and so on:

let str = "abcdefg";
str.slice(1,6);   // 输出结果:"bcdef" 
str.slice(1);     // 输出结果:"bcdefg" 
str.slice();      // 输出结果:"abcdefg" 
str.slice(-2);    // 输出结果:"fg"
str.slice(6, 1);  // 输出结果:""

Note that the substring returned by this method includes the characters at the beginning , but not the characters at the end .

2、substr()

The substr() method is used to extract the specified number of characters starting from the starting subscript in the string. Its syntax is as follows:

string.substr(start,length)

This method has two parameters:

  • start is required. The starting subscript of the substring to be extracted. Must be a numeric value. If negative, the parameter specifies the position from the end of the string. That is, -1 refers to the last character in the string, -2 refers to the second-to-last character, and so on.
  • length: optional. The number of characters in the substring. Must be a numeric value. If this parameter is omitted, returns the string from the beginning to the end of stringObject.
let str = "abcdefg";
str.substr(1,6); // 输出结果:"bcdefg" 
str.substr(1);   // 输出结果:"bcdefg" 相当于截取[1,str.length-1]
str.substr();    // 输出结果:"abcdefg" 相当于截取[0,str.length-1]
str.substr(-1);  // 输出结果:"g"

3、substring()

The substring() method is used to extract characters between two specified subscripts in a string. Its syntax is as follows:

string.substring(from, to)

This method has two parameters:

  • from: required. A non-negative integer specifying the position in string of the first character of the substring to be extracted.
  • to: optional. A non-negative integer, one more than the position in string of the last character of the substring to be extracted. If this parameter is omitted, the returned substring will go up to the end of the string.

Note: If the parameters from and to are equal, then the method returns an empty string (that is, a string with a length of 0). If from is greater than to, the method swaps the two parameters before extracting the substring. And this method does not accept negative parameters, if the parameter is a negative number, it will return this string.

let str = "abcdefg";
str.substring(1,6); // 输出结果:"bcdef" [1,6)
str.substring(1);   // 输出结果:"bcdefg" [1,str.length-1]
str.substring();    // 输出结果:"abcdefg" [0,str.length-1]
str.substring(6,1); // 输出结果 "bcdef" [1,6)
str.substring(-1);  // 输出结果:"abcdefg"

Note that the substring returned by this method includes the characters at the beginning , but not the characters at the end .

7. Change the upper and lower case of the string

The toLowerCase() and toUpperCase() methods can be used for case conversion of strings.

1、toLowerCase()

toLowerCase(): This method is used to convert the string to lowercase.

let str = "adABDndj";
str.toLowerCase(); // 输出结果:"adabdndj"

2、toUpperCase()

toUpperCase(): This method is used to convert the string to uppercase.

let str = "adABDndj";
str.toUpperCase(); // 输出结果:"ADABDNDJ"

We can use this method to capitalize the first letter of a string:

let word = 'apple'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // 输出结果:"Apple"

8. String pattern matching

The replace(), match(), and search() methods can be used to match or replace characters.

1、replace()

replace(): This method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression. Its syntax is as follows:

string.replace(searchvalue, newvalue)

This method has two parameters:

  • searchvalue: Required. A RegExp object specifying a substring or pattern to replace. If the value is a string, it is used as the literal text pattern to be retrieved without first being converted to a RegExp object.
  • newvalue: Required. a string value. Specifies replacement text or a function that generates replacement text.
let str = "abcdef";
str.replace("c", "z") // 输出结果:abzdef

Perform a global replace, 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'

Note: If the regexp has the global flag g, the replace() method will replace all matching substrings. Otherwise, it just replaces the first matching substring.

2、match()

match(): This method is used to retrieve a specified value within a string, or to find a match of one or more regular expressions. This method is like indexOf() and lastIndexOf(), but it returns the specified value instead of the string position. Its syntax is as follows:

string.match(regexp)

The method's argument regexp is required, a RegExp object specifying 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 this 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]

3、search()

The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. Its syntax is as follows:

string.search(searchvalue)

The parameter regex of this method can be a substring to be retrieved in string, or a RegExp object to be retrieved.

Note: To perform a case-insensitive search, append the flag i. This method does not perform global matching, it will ignore the flag g, that is, it will only return the result of the first successful match. Returns -1 if no matching substring is found.

Return value: Return the starting position of the first substring matching regexp in str.

let str = "abcdef";
str.search(/bcd/)   // 输出结果:1

Nine, remove the trailing blank character of the string

The trim(), trimStart(), and trimEnd() methods can be used to remove the leading and trailing blanks at the beginning and end of a string. The blanks include: spaces, tabs, newlines, and other blanks.

1、trim()

The trim() method is used to remove the leading and trailing whitespace characters of the string, this method will not change the original string:

let str = "  abcdef  "
str.trim()    // 输出结果:"abcdef"

Note that this method is not applicable to null, undefined, and Number types.

2、trimStart()

The trimStart() method behaves the same as 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  "

3、trimEnd()

The trimEnd() method behaves the same as 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"

10. Get the string itself

The valueOf() and toString() methods both return the value of the string itself, which is not very useful.

1、valueOf()

valueOf(): returns the original value of a string object, this method is usually called automatically by JavaScript, rather than explicitly in the code.

let str = "abcdef"
console.log(str.valueOf()) // "abcdef"

2、toString()

toString(): returns the string object itself

let str = "abcdef"
console.log(str.toString()) // "abcdef"

11. Repeat a string

The repeat() method returns a new string, which means repeating the original string n times:

'x'.repeat(3)     // 输出结果:"xxx"
'hello'.repeat(2) // 输出结果:"hellohello"
'na'.repeat(0)    // 输出结果:""

If the argument is a decimal, it will be rounded down:

'na'.repeat(2.9) // 输出结果:"nana"

If the parameter is negative or Infinity, an error will be reported:

'na'.repeat(Infinity)   // RangeError
'na'.repeat(-1)         // RangeError

Equivalent to 0 if the argument is a decimal between 0 and -1, since rounding occurs first. Decimals between 0 and -1, equal to -0 after rounding, repeat as 0.

'na'.repeat(-0.9)   // 输出结果:""

If the argument is NaN, it is equivalent to 0:

'na'.repeat(NaN)    // 输出结果:""

If the repeat parameter is a string, it will be converted to a number first.

'na'.repeat('na')   // 输出结果:""
'na'.repeat('3')    // 输出结果:"nanana"

12. Complete the length of the string

The padStart() and padEnd() methods are used to pad the length of the string. If a string is not long enough, it will be completed at the head or tail.

1、padStart()

padStart() is used for header completion. This method has two parameters, the first parameter is a number, indicating the length of the string after completion; the second parameter 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'

If the sum of the lengths of the string used for completion and the original string exceeds the specified minimum length, the completed string exceeding the number of digits will be truncated:

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

If the second parameter is omitted, the length is filled with spaces by default:

'x'.padStart(4) // '   x'

The common use of padStart() is to specify the number of digits for value completion. One of the author's recent needs is to fill the returned page number with three digits. For example, the first page is displayed as 001. You can use this method to operate:

"1".padStart(3, '0')   // 输出结果: '001'
"15".padStart(3, '0')  // 输出结果: '015'

2、atEnd()

padEnd() is used for tail completion. This method also receives two parameters, the first parameter is the maximum length of string completion, and the second parameter is the string used for completion:

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

Thirteen, string to number

Both parseInt() and parseFloat() methods are used to convert strings to numbers.

1、parseInt()

The parseInt() method is used to parse a string and return an integer. Its syntax is as follows:

parseInt(string, radix)

This method has two parameters:

  • string: required. The string to be parsed.
  • radix: optional. Indicates the base of the number to parse. The value is between 2 ~ 36.

When the value of parameter radix is ​​0, or this parameter is not set, parseInt() will judge the radix of the number according to string.

parseInt("10");			  // 输出结果:10
parseInt("17",8);		  // 输出结果:15 (8+7)
parseInt("010");		  // 输出结果:10 或 8

When the value of the parameter radix starts with "0x" or "0X", it will be base 16:

parseInt("0x10")      // 输出结果:16

If the argument is less than 2 or greater than 36, parseInt() will return NaN:

parseInt("50", 1)      // 输出结果:NaN
parseInt("50", 40)     // 输出结果:NaN

Only the first number in the string will be returned, until the first character that is not a number:

parseInt("40 4years")   // 输出结果:40

Whitespace at the beginning and end of the string is allowed:

parseInt("  60  ")    // 输出结果: 60

2、parseFloat()

The parseFloat() method parses a string and returns a float. This method specifies whether the first character in the string is a number. If so, the string is parsed until the end of the number is reached, and the number is returned as a number, not as a string. Its syntax is as follows:

parseFloat(string)

parseFloat parses its string argument into a float and returns it. If parsing encounters a character other than a sign (+ or -), digit (0-9), decimal point, or exponent (e or E) in scientific notation, it ignores that character and beyond All characters of , returns the currently parsed floating-point number. At the same time, the leading blank character in the parameter string will be ignored.

parseFloat("10.00")      // 输出结果:10.00
parseFloat("10.01")      // 输出结果:10.01
parseFloat("-10.01")     // 输出结果:-10.01
parseFloat("40.5 years") // 输出结果:40.5

parseFloat returns NaN if the first character of the argument string cannot be parsed as a number.

parseFloat("new40.5")    // 输出结果:NaN

The original text comes from:   JavaScript 28 common string methods and usage skills - Nuggets  

Guess you like

Origin blog.csdn.net/weixin_64051447/article/details/130718513