Summary of front-end string methods

1. length attribute

const sss = 'length'
    console.log('字符串长度是', sss.length)

2、chartAt()  

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

  • The charAt() method obtains the character at the specified position;
  • The charCodeAt() method obtains the Unicode value of the character at the specified position.
console.log('e的相应的位置呢', sss.charAt('e'))
console.log('相应的Unicode', sss.charCodeAt('e'))

 3. Retrieve whether the string contains a specific sequence

These 5 methods can all be used to retrieve whether a string contains a specific sequence. The first two methods get the index value of the specified element, and will only return the position of the first matched value. The last three methods return Boolean values, indicating whether the specified value is matched.

indexOf()

indexOf(): Search for a certain character, returns the first matched position, otherwise -1 is returned. The syntax is as follows: < /span>

console.log('获取相应的位置', sss.indexOf('e')) 

lastIndexOf()

lastIndexOf(): Search for a certain character, if found, return the last matched position, otherwise return -1

console.log('获取相应的最后的位置', sss.lastIndexOf('e'))

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 this method is as follows:

console.log('获取相应的字符串是否存在', sss.includes('en'), sss.includes('ao'))

console.log('获取相应的字符串是否存在', sss.includes('en', 8))  // 8为起始位置

startsWith()

startsWith(): This method is used to detect whether the string begins with the specified substring. Returns true if it starts with the specified substring, false otherwise. Its syntax is the same as the includes() method above.

console.log('startsWith获取相应的字符串是否存在', sss.startsWith('le'), sss.startsWith('ao'))

console.log('startsWith获取相应的字符串是否存在', sss.startsWith('g', 3)) // 3为起始位置

endsWith()

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

console.log('endsWith获取相应的字符串是否存在', sss.endsWith('e'), sss.endsWith('h', 5), sss.endsWith('h', 4))

4. 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 concatenated with two or more strings. Its syntax is as follows:

console.log('连接字符串', sss.concat('a', 'b', 'c', 'e', 'f', 'm'))

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

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. Its syntax is as follows:

string.split(separator,limit)

This method has two parameters:

  • separator: required. A string or regular expression that splits the string at the location 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.
console.log('字符串获取相应的数组', sss.split('g'), sss.split('', 3), sss.split(''))
const list = 'apples,bananas;cherries'
    const fruits = list.split(/[,;]/)
    console.log(fruits)

6. Intercept string

The substr(), substring() and slice() methods can all be used to intercept strings.

(1) slice()

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

console.log('slice使用', sss.slice(1, 2))

(2) substr()

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

console.log('substr使用', sss.substr(1, 2))

(3) substring()

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

console.log('substring使用', sss.substring(1, 2))

7. String case conversion

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

const bbbb = 'abcEDFhi'
    console.log('toLowerCase与toUpperCase', bbbb.toLowerCase(), bbbb.toUpperCase())

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:

const str = 'Mr Blue has a blue house and a blue car'
    console.log('replace', str.replace(/blue/gi, 'red'))

(2)match()

match(): This method is used to retrieve a specified value within a string, or 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. Its syntax is as follows:

const str1 = 'abcdef'
    console.log(str1.match('c'))

(3)search()

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

const str2 = 'abcdef'
    console.log(str2.search(/bcd/)) // 输出结果:1

9. Remove trailing whitespace characters from strings

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

(1)trim()

The trim() method is used to remove leading and trailing whitespace characters from a string. This method does not change the original string:

const list2 = ' acb '
    console.log('trim', list2.trim(), list2.trim().length)

(2)trimStart()

The trimStart() method behaves the same astrim(), but returns a new string with whitespace removed from the beginning of the original string. , the original string will not be modified:

const list2 = ' acb '
    console.log('trim', list2.trim(), list2.trim().length, list2.trimStart(), list2.trimStart().length)

(3)trimEnd()

The trimEnd() method behaves the same astrim(), but returns a new string with whitespace removed from the end of the original string. , the original string will not be modified:

const list2 = ' acb '
    console.log('trim', list2.trim(), list2.trim().length, list2.trimStart(), list2.trimStart().length, list2.trimEnd(), list2.trimEnd().length)

10. Get the string itself

The valueOf() and toString() methods both return the value of the string itself, which seems to be of little use.

(1)valueOf()

valueOf(): Returns the raw 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)    // 输出结果:""
'na'.repeat(2.9) // 输出结果:"nana"
'na'.repeat(Infinity)   // RangeError
'na'.repeat(-1)         // RangeError

12. Complement the string length

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()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(4, 'ab') // 'abax'

A common use of padStart() is to specify the number of digits for numerical completion. One of the recent requirements of the author is to complete the returned page number to three digits. For example, page 1 is displayed as 001, and you can use this method to operate:

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

(2)atEnd()

padEnd()Used for tail completion. This method also receives 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:

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

13. Convert string to number

The parseInt() and parseFloat() methods are both 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:

This method has two parameters:

  • string: required. The string to be parsed.
  • radix: optional. Represents the base of the number to be parsed. The value is between 2 ~ 36.
console.log(parseInt('10'))	 // 输出结果:10
    console.log(parseInt('17',8))	// 输出结果:15 (8+7)
    console.log(parseInt('010')) // 输出结果:10 或 8
(2)parseFloat()

The parseFloat() method parses a string and returns a floating point number. This method specifies whether the first character in the string is a number. If it is, the string is parsed until it reaches the end of the number, and the number is returned as a number rather than as a string. Its syntax is as follows:

console.log(parseFloat('10.00')) // 输出结果:10.00
    console.log(parseFloat('10.01')) // 输出结果:10.01
    console.log(parseFloat('-10.01')) // 输出结果:-10.01
    console.log(parseFloat('40.5 years')) // 输出结果:40.5

Some related classic cases on the use of string methods

A collection of methods for removing spaces from strings on the front end_Removing spaces in strings on the front end-CSDN Blog

Supongo que te gusta

Origin blog.csdn.net/2201_75705263/article/details/134539164
Recomendado
Clasificación