The most complete js string operation method

Keywords: Javascript

Every time I use the string method of js, I have to search now. I can finally learn it today
This article is transferred from https://juejin.cn/post/7010928535053271077#heading-20

1. Get string length

const str = "hello",
str.length

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

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

(1)charAt()

const str = 'hello';
str.charAt(1)  // Output result: e 
const str = 'hello';
str.charAt(1)  // Output result: e 
str[1]         // Output result: e 
str.charAt(5)  // Output result: '' 
str[5]         // Output result: undefined

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, and charAt(index) is compatible.

(2)charCodeAt()

charCodeAt(): this method will return the Unicode value of the character at the specified index position. The return value is an integer between 0 and 65535

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

3. Whether the retrieval string contains a specific sequence

(1)indexOf()

Find a character, if any, the first matching position is returned, otherwise - 1 is returned,

string.indexOf(searchvalue,fromindex)
  • searchvalue: required; specifies the string value to be retrieved;
  • fromindex: an optional integer parameter that specifies the position in the string where retrieval starts. Its legal value is 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"));   // Output result: 0
console.log(str.indexOf("z"));   // Output result: - 1
console.log(str.indexOf("c", 4)) // Output result: 9

(2)lastIndexOf()

Find a character, if any, return the last matching position, otherwise return - 1

let str = "abcabc";
console.log(str.lastIndexOf("a"));  // Output result: 3
console.log(str.lastIndexOf("z"));  // Output result: - 1

(3)includes()

This method is used to determine whether the string contains the specified substring. Returns true if a matching string is found, otherwise false.

string.includes(searchvalue, start)
  • searchvalue: required, the string to find;
  • Start: optional. Set the location from which to start searching. The default value 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

(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. The syntax is the same as the include () method above.

let str = 'Hello world!';
str.startsWith('Hello') // Output result: true
str.startsWith('Helle') // Output result: false
str.startsWith('wo', 6) // Output result: true

(5)endsWith()

endsWith(): this method is used to determine whether the current string ends with the specified substring. Returns true if the incoming substring is at the end of the search string, otherwise false.

string.endsWith(searchvalue, length)
  • searchvalue: required, the substring to search;
  • Length: sets the length of the string. The default value is the original string length string.length.
let str = 'Hello world!';

str.endsWith('!')       // Output result: true
str.endsWith('llo')     // Output result: false
str.endsWith('llo', 5)  // Output result: true

4. Connect multiple strings

The concat() method is used to connect two or more strings. This method does not change the original string, but returns a new string connecting two or more strings.

string.concat(string1, string2, ..., stringX)
let str = "abc";
console.log(str.concat("efg"));          //Output result: "abcefg"
console.log(str.concat("efg","hijk")); //Output result: "abcefghijk"

5. Split string into array

The split() method is used to split a string into an array of strings. This method does not change the original string.

string.split(separator,limit)
  • separator: required. String or regular expression that splits the string from the place specified by the 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");    // Output result: ["ab", "def"]
str.split("", 4)   // Output result: ['a ',' B ',' C ','d'] 

If you use an empty string as a separator, each character in the string will be split.

str.split("");     // Output result: ["a", "b", "c", "d", "e", "f"]

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

const list = "apples,bananas;cherries"
const fruits = list.split(/[,;]/)
console.log(fruits);  // Output result: ["apples", "bananas", "cherries"]

6. Intercept string

(1) slice()

The slice() method is used to extract a part of a string and return the extracted part with a new string.

string.slice(start,end)
  • start: required. The starting subscript of the fragment to be intercepted, and the first character position is 0. If it is negative, it is truncated from the tail.
  • End: optional. The subscript at the end of the fragment to be intercepted. If this parameter is not specified, the substring to be extracted includes
let str = "abcdefg";
str.slice(1,6);   // Output result: "bcdef" 
str.slice(1);     // Output result: "bcdefg" 
str.slice();      // Output result: "abcdefg" 
str.slice(-2);    // Output result: "fg"
str.slice(6, 1);  // Output result: ''

The substring returned by this method includes the character at the beginning, but does not include the character at the end.

(2) substr()

The substr() method is used to extract a specified number of characters from the string starting from the starting subscript.

string.substr(start,length)
  • start is required. The starting subscript of the substring to extract. Must be numeric. If it is negative, the parameter declares the position from the end of the string. That is, - 1 refers to the last character in the string, - 2 refers to the penultimate character, and so on.
  • length: optional. The number of characters in the substring. Must be numeric. If this parameter is omitted, the string from the beginning to the end of the stringObject is returned.
let str = "abcdefg";
str.substr(1,6); // Output result: "bcdefg" 
str.substr(1);   // Output result: "bcdefg" is equivalent to intercepting [1,str.length-1]
str.substr();    // Output result: "abcdefg" is equivalent to intercepting [0,str.length-1]
str.substr(-1);  // Output result: "g"

(3) substring()

The substring() method is used to extract the character of the string between two specified subscripts.

string.substring(from, to)
  • from: required. A nonnegative integer that specifies the position of the first character of the substring to be extracted in the string.
  • To: optional. A nonnegative integer, 1 more than the position of the last character of the substring to be extracted in the string. If this parameter is omitted, the returned substring will continue to the end of the string.
let str = "abcdefg";
str.substring(1,6); // Output result: "bcdef" [1,6)
str.substring(1);   // Output result: "bcdefg" [1,str.length-1]
str.substring();    // Output result: "abcdefg" [0,str.length-1]
str.substring(6,1); // Output result "bcdef" [1,6)
str.substring(-1);  // Output result: "abcdefg"

The substring returned by this method includes the character at the beginning, but does not include the character at the end.

difference

slice() is different from the second parameter of substr()

substr() and substring() include characters at the end of whether or not

7. String case conversion

(1)toLowerCase()

toLowerCase(): this method is used to convert a string to lowercase.

let str = "adABDndj";
str.toLowerCase(); // Output result: "adabdndj"

(2)toUpperCase()

toUpperCase(): this method is used to convert a string to uppercase.

let str = "adABDndj";
str.toUpperCase(); // Output result: "ADABDNDJ"

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

let word = 'apple'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // Output result: "Apple"

8. String pattern matching

(1)replace()

replace(): this method is used to replace some characters with others in a string, or to replace a substring that matches a regular expression.

string.replace(searchvalue, newvalue)
  • searchvalue: required. A RegExp object that specifies a substring or a pattern to replace. If the value is a string, it is treated as the direct text pattern to retrieve, rather than being first converted to a RegExp object. (RegExp object is a regular expression)
  • newvalue: required. A string value. Specifies the replacement text or the function that generates the replacement text.
let str = "abcdef";
str.replace("c", "z") // Output result: abzdef

Perform a global replace, ignoring case:

let str="Mr Blue has a blue house and a blue car";
str.replace(/blue/gi, "red");    // Output result: 'Mr red has a red house and a red car'

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

(2)match()

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

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 substring specified in a string or a substring that matches a regular expression.

string.search(searchvalue)
let str = "abcdef";
str.search(/bcd/)   // Output result: 1

Returns the starting position of the first substring in str that matches regexp.

Note: to perform case insensitive retrieval, 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 matching. If no matching substring is found, - 1 is returned.

9. Remove string closing whitespace

(1)trim()

The trim() method is used to remove whitespace at the beginning and end of a string

let str = "  abcdef  "
str.trim()    // Output result: "abcdef"

Note that this method does not apply to null, undefined, Number types.

(2)trimStart()

The behavior of the trimStart() method is the same as that of trim(), but it will return a new string that removes white space from the beginning of the original string and will not modify the original string

const s = '  abc  ';
s.trimStart()   // "abc  "

(3)trimEnd()

The behavior of the trimEnd() method is the same as that of trim(), but it will return a new string that removes white space from the end of the original string and will not modify the original string

const s = '  abc  ';
s.trimEnd()   // "  abc"

10. Get the string itself

(1)valueOf()

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

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.valueOf(); //Banana,Orange,Apple,Mango

(2)toString()

toString(): returns the string object itself and converts other types of data into strings

let str = "abcdef",str2 =123123123
console.log(str.toString()) // "abcdef"
console.log(typeof(str2.toString())) //string

typeof() view data types

11. Repeat a string

The repeat() method returns a new string, indicating that the original string is repeated n times

'x'.repeat(3)     // Output result: "xxx"
'hello'.repeat(2) // Output result: "hello hello"
'na'.repeat(0)    // Output result: ''

If the parameter is decimal, it will be rounded down

'na'.repeat(2.9) // Output result: "nana"

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

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

If the parameter is a decimal between 0 and - 1, it is equivalent to 0 because the rounding operation will be performed first. The decimal between 0 and - 1 is equal to - 0 after rounding, and repeat is regarded as 0.

'na'.repeat(-0.9)   // Output result: ''

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

'na'.repeat(NaN)    // Output result: ''

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

'na'.repeat('na')   // Output result: ''
'na'.repeat('3')    // Output result: "Nana"

12. Complement string length

(1)padStart()

For head completion. The method has two parameters. The first parameter is a number, which represents the length of the string after completion; The second parameter is the string used to complete

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

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

"1".padStart(3, '0')   // Output result: '001'
"15".padStart(3, '0')  // Output result: '015'

(2)padEnd()

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 to complete

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

13. Convert string to number

(1)parseInt()

parseInt(string, radix)
  • String: required. The string to be parsed.
  • Radio: optional. Represents the cardinality of the number to parse. The value is between 2 and 36.

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

parseInt("10");			  // Output result: 10
parseInt("17",8);		  // Output result: 15 (8 + 7)
parseInt("010");		  // Output result: 10

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

parseInt("0x10")      // Output result: 16

If the parameter is less than 2 or greater than 36, parseInt() returns NaN:

parseInt("50", 1)      // Output result: NaN
parseInt("50", 40)     // Output result: NaN

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

parseInt("40 4years")   // Output result: 40

NaN is returned if the first character of the string cannot be converted to a number:

parseInt("new100")     // Output result: NaN

Spaces at the beginning and end of a string are allowed:

parseInt("  60  ")    // Output result: 60

(2)parseFloat()

The parseFloat() method parses a string and returns a floating point number.

parseFloat("10.00")      // Output result: 10.00
parseFloat("10.01")      // Output result: 10.01
parseFloat("-10.01")     // Output result: - 10.01
parseFloat("40.5 years") // Output result: 40.5

parseFloat returns NaN if the first character of the parameter string cannot be parsed into a number.

parseFloat("new40.5")    // Output result: NaN

Posted by jmdavis on Sat, 25 Sep 2021 00:07:02 -0700