preface

Recently, I reviewed the string method in JavaScript. In order to avoid forgetting it and to be able to review it in time, I hereby summarize.

Character methods charAt() & charCodeAt()

Both charAt() and charCodeAt() are used to access a particular character in a string, both take an argument based on the character position of 0, and both try to convert the received argument to type Number before the method executes. The difference is that charAt() returns the character at a given position as a single-character string, whereas charCodeAt() returns the character encoding.

If you pass in a parameter of type Number or a parameter that can be converted to type Number.

console.log('abcdef'.charAt(3)) //d
console.log('abcdef'.charCodeAt(3)) //100
Copy the code

If an argument is passed that cannot be converted to Number, charAt() returns the first character of the checked string, and charCodeAt() returns the character encoding of one character of the checked string.

console.log('abcdef'.charAt('3')) //d
console.log('abcdef'.charCodeAt('3')) //100
console.log('abcdef'.charAt('a')) //a
console.log('abcdef'.charCodeAt('a')) //97
Copy the code

Concat () & slice() & substr() & subString()

Concat () can take one or more arguments and concatenate them, returning the concatenated new string.

console.log('abc'.concat('def')) //abcdef
Copy the code

The slice(), substr(), and subString() methods each take one or two arguments and return a subString of the operated string. The first argument to each of these methods specifies the start position of the substring. The second argument to slice() and substring() specifies the position after the last character of the substring. The second argument to substr() specifies the number of characters to return.

console.log('abcdef'.slice(1, 3)) //bc
console.log('abcdef'.substring(1, 3)) //bc
console.log('abcdef'.substr(1, 3)) //bcd
Copy the code

In the absence of a second argument, all three methods default to the end of the string.

console.log('abcdef'.slice(1)) //bcdef
console.log('abcdef'.substring(1)) //bcdef
console.log('abcdef'.substr(1)) //bcdef
Copy the code

In the case of passing negative values, slice() adds the incoming negative value to the length of the string, substr() adds the negative first argument to the length of the string, and substring() converts the second argument to 0, and substring() converts all negative values to 0.

console.log('abcdef'.slice(-2)) //ef console.log('abcdef'.slice(-4, -2)) //cd console.log('abcdef'.substr(-2)) //ef console.log('abcdef'.substr(-2, Log ('abcdef'. Substring (-2)) //abcdef console.log('abcdef'. Substring (-2, -2))) // Empty stringCopy the code

In the case of argument one > argument two, slice(),substr() returns an empty string, and substring() starts with a smaller number and ends with a larger number.

Log ('abcdef'.slice(2, 0)) // Empty string console.log('abcdef'.substr(2, 0)) // Empty string console.log('abcdef'.substring(2, 0)) // empty string console.log('abcdef'.substring(2, 0)) 0)) //abCopy the code

Position methods indexOf() & lastIndexOf()

Both methods search for a given substring from the string and return the location of the substring, or -1 if it is not found. The difference between these two methods is that indexOf() searches substrings backwards from the beginning of the string, while lastIndexOf() does the opposite.

console.log('abcabc'.indexOf('a')) //0
console.log('abcabc'.lastIndexOf('a')) //3
Copy the code

trim()

Trim () creates a copy of the string, removing all prefixes and postfixes, and returns the result.

console.log(' a  b  c  '.trim()) //a  b  c
Copy the code

ToLowerCase () & toUpperCase() & toLocaleUpperCase()

ToUpperCase ()toLocaleUpperCase() is the method to convert lowercase toUpperCase, and toLowerCase() and toLocaleLowerCase() are the methods to convert uppercase toLowerCase. ToUpperCase () and toLowerCase(), while toLocaleUpperCase() and toLocaleLowerCase() are intended for locale-specific implementations.

console.log('abcdef'.toUpperCase()) //ABCDEF
console.log('abcdef'.toLocaleUpperCase()) //ABCDEF
console.log('ABCDEF'.toLowerCase()) //abcdef
console.log('ABCDEF'.toLocaleLowerCase()) //abcdef
Copy the code

String pattern matching methods match() & search() & replace() & htmlEscape() & split()

The match() method takes either a regular expression string or a RegExp object and returns an array containing the results of the match. If no match is found, the return value is null.

console.log('abcabc'.match(/a/).index) //0
Copy the code

The search() method always matches the pattern backwards from the beginning of the string, receiving either a regular expression string or a RegExp object, returning the index of the position of the pattern’s first match, or -1 if none is found.

console.log('abcabc'.search(/a/)) //0
Copy the code

The replace() method can perform string replacements. The method takes two arguments, the first being a RegExp object or a string, and the second being a string or function that returns a copy of the string after the replacement operation. If the first argument is a string, only the first substring is replaced. If you want to replace all strings, you can do so by passing in a regular expression with a global tag.

console.log('abcabc'.replace('a', 'x')) //xbcabc
console.log('abcabc'.replace(/a/g, 'x')) //xbcxbc
Copy the code

If the first argument is a string, you can also use some special character sequences, which are recommended in the MDN documentation. String.prototype.replace() – JavaScript | MDN

If the second argument is a function, the function is executed when the match starts, and the function returns the value as the replacement string. This function takes three arguments: the pattern’s match, the pattern’s position in the string, and the original string.

console.log('abcabc'.replace(/a/g, function (match, pos, originalText) {
        return 'x'
    })
) //xbcxbc
Copy the code

Split () splits a string into multiple substrings based on the specified delimiter and puts the result in an array. The method takes one or two arguments. The first argument is a delimiter, which can be a string or a RegExp object, and the second argument specifies the size of the array.

console.log('a,b,c'.split(',')) //["a", "b", "c"]
console.log('a,b,c'.split(',', 2)) //["a", "b"]
console.log('a,b,c'.split(/,/)) //["a", "b", "c"]
Copy the code

localeCompare()

LocaleCompare () compares two strings and returns a negative number if the string should precede the string argument in the alphabet; If the string is equal to the string argument, 0 is returned; Returns a positive number if the string should be ranked after the string argument in the alphabet.

console.log('a'.localeCompare('b')) //-1
console.log('a'.localeCompare('a')) //0
console.log('b'.localeCompare('a')) //1
Copy the code

fromCharCode()

Takes one or more character encodings, and then converts them to a string that cannot recognize code points greater than 0xFFFF.

console.log(String.fromCharCode(97, 98, 99, 100, 101, 102)) //abcdef
Copy the code

HTML method

HTML formatting task methods. A book or document is recommended for this section.

HTML wrapper methods

ES6

fromCodePoint()

This method is used to return corresponding characters from Unicode code points and can recognize characters greater than 0xFFFF.

// console.log(string.fromCharCode (0x10000)) // Empty String // console.log(string.fromcodePoint (0x10000)) //𐀀Copy the code

raw()

This method returns a string with all the slashes escaped, or escaped again if the original string’s slashes have been escaped. Usually used for template strings.

console.log(String.raw`Hi\n${1 + 2}`) //Hi\n3
Copy the code

codePointAt()

Because inside JavaScript, characters are stored in UTF-16 format, each character is fixed at 2 bytes. For characters with Unicode code points greater than 0xFFFF, JavaScript treats them as two characters. CharCodeAt () can only return the first two bytes and the last two bytes respectively, and can’t handle 4-byte characters correctly. CharPointAt () solves this problem.

Var STR = '𠮷' console.log(str.charcodeat (0)) //55362 console.log(str.charcodeat (1)) //57271 console.log(str.codePointAt(0)) //134071 console.log(str.codePointAt(1)) //57271Copy the code

For character encodings, it is recommended to read character encodings notes: ASCII, Unicode, and UTF-8

normalize()

This method is used to unify different representations of characters into the same form. For this section, the introduction to ECMAScript6 is recommended.

Example method: normalize()

includes() & startsWith() & endsWith()

Includes () is used to determine whether a string is included in another string, returning a Boolean value.

console.log('abcdef'.includes('cd')) //true
Copy the code

StartsWith () is used to determine whether the argument string is at the head of the original string, returning a Boolean value.

console.log('abcdef'.startsWith('abc')) //true
Copy the code

EndsWith () is used to determine whether the argument string is at the end of the original string and returns a Boolean value.

console.log('abcdef'.endsWith('def')) //true
Copy the code

repeat()

This returns a new string, repeating the original string n times.

console.log('abc'.repeat(3)) //abcabcabc
Copy the code

If the argument is a decimal, it is rounded.

The console. The log (' ABC '. Repeat (1.6)) / / ABCCopy the code

If it’s negative or Infinity, an error is reported.

console.log('abc'.repeat(-1)) // RangeError
console.log('abc'.repeat(Infinity)) // RangeError
Copy the code

If the argument is a decimal or NaN between 0 and -1, it is equal to 0.

The console. The log (' ABC '. Repeat (0.1)). / / the console log (' ABC '. Repeat (NaN)) / /Copy the code

ES8

padStart() & padEnd()

These methods are used to populate the specified string at the head or end of the string, returning a new string. Both methods take two arguments, the first being the maximum length that string completion takes effect, and the second being the string used for completion. The difference is that padStart() is used for head completion and padEnd() for tail completion.

console.log('abc'.padStart(6, 'x')) //xxxabc
console.log('abc'.padEnd(6, 'x')) //abcxxx
Copy the code

If the original string length is equal to or greater than the maximum length, the original string is returned.

console.log('abc'.padStart(3, 'x')) //abc
Copy the code

If the length of the completed string and the original string is greater than the maximum length, the excess portion of the completed string is intercepted.

console.log('abc'.padStart(5, 'xxx')) //xxabc
Copy the code

If the second argument is omitted, the default is to complete the length with a space.

console.log('abc'.padStart(6)) //    abc
Copy the code

ES10

trimStart() & trimEnd()

The trimStart() method removes whitespace from the beginning of the string, and the trimEnd() method removes whitespace from the right end of a string.

console.log('   abc   '.trimStart()) //abc
console.log('   abc   '.trimEnd()) //   abc
Copy the code

ES11

matchAll()

The matchAll() method returns a traverser that contains all the matching regular expressions and the results of the grouped capture. Because it returns a traverser, it is usually used for… Of loop out.

for (const match of 'abcabc'.matchAll(/a/g)) {
    console.log(match)
}
//["a", index: 0, input: "abcabc", groups: undefined]
//["a", index: 3, input: "abcabc", groups: undefined]
Copy the code

ES12

replaceAll()

ReplaceAll () replaces all matches at once. Like replace(), this method takes two arguments, the first of which is a RegExp object or a string (the character to be replaced), and the second argument can be a string (the replacement text) or a function that returns a string after the replacement operation. The difference is that if it is a RegExp object without the G modifier, an error is reported.

console.log('abcabc'.replaceAll('a', 'x')) //xbcxbc
Copy the code

In addition, the second argument to replaceAll() can use some special strings.

  • $& : Matching substring.
  • $’ : Matches the text before the result.
  • $’ : the text following the match result.
  • $n: the NTH group of contents to be matched successfully. N is a natural number starting from 1. This parameter is valid only if the first parameter is a regular expression.
  • $$: indicates the dollar sign $.
console.log('abc'.replaceAll('b', '$&')) //abc
console.log('abc'.replaceAll('b', '$`')) //aac
console.log('abc'.replaceAll('b', `$'`)) //acc
console.log('abc'.replaceAll(/(a)(b)/g, '$2$1')) //bac
console.log('abc'.replaceAll('b', '$$')) //a$c
Copy the code

At the end

This article summarizes the basic use of JavaScript string methods. If you want to learn more, check out the Little Red Book, Rhino Book, or getting started with the ES6 standard. Please correct any deficiencies or mistakes.

The resources

  • JavaScript Advanced Programming (Version 4)
  • Introduction to ES6 Standards (3rd Edition)
  • MDN