js string method

Keywords: Javascript ECMAScript

String operation method

1. Convert to string type toString()

(1)var num=110;
  var n=num.toString();    //"110"
(2)var num=111;
var n=String(num);       //"111"
(3)var num=112;
var n="" + num;          //"112"

2. String segmentation returns a new array split()

(1)var str="qingchenghuwoguoxiansheng,woaishenghuo,woaiziji";
var arr1=str.split(",");    //["qingchenghuwoguoxiansheng","woaishenghuo","woaiziji"];
Var arr2=str.split("");        //["q","i","n","g","c","h","e","n","g","h","u","w","o","g","u","o","x","i","a","n","s","h","e","n","g",",","w","o","a","i","s","h","e","n","g","h","u","o",",","w","o","a","i","z","i","j","i"];
(2)split()The second parameter of represents the maximum length of the returned string array
    var str="qingchenghuwoguoxiansheng,woaishenghuo,woaiziji";
var arr1=str.split(",",2); //["qingchenghuwoguoxiansheng","woaishenghuo"];
var arr2=str.split("",8); //["q","i","n","g","c","h","e","n"];

3. See 4.23 for string replacement

4. Query string indexOf(), lastIndexOf()

  • Determine whether the string contains substrings
  • (1) indexOf(), which is case sensitive. Returns the index of the first occurrence of a substring in a string (search from left to right). If there is no match, - 1 is returned
  • (2) lastIndexOf(), which is case sensitive. Returns the index of the last occurrence of a substring in the string (search from right to left). If there is no match, returns - 1.

5. Return the character at the specified position or its character encoding values charAt(), charCodeAt()

(1)var str="Hello World!";
     var index=str.charAt(7); //o
 Find the seventh bit in the whole string (the index is found)
(2)Find the encoding value of the character corresponding to the position
    var str="Hello World!";
var charCode=str. charCodeAt(7);    //111

6. String match()

Match function  match();
var str="hi,mynameisguoxiansheng6,33iswho?";
var n=str.match("guo");    //guo
var n1=str.match("Guo");    //null
var zz1=/\d+/g;//Regularization determines the number of global matching 0-9
var zz2=/guo/g;//Regularization determines the global matching guo
var zz3=/guo/;
var n2=str.match(zz1);    //["6","33"]
var n3=str.match(zz2);    //["guo"]
var n3=str.match(zz3);    //["Guo", index: 11, input: "Hi, mynameisguoxiansheng6,33iswho?"] the subscript of the Guo letter is in the 11th position and returns the original string;
n3.index    //11
n3.input    //hi,mynameisguoxiansheng6,33iswho?
match Function is called on a string
 When the matched string contains the string to be matched, the string to be matched is returned
 If a regular matching string is used, if the regular expression does not g (Global identity)Flag to return the same result as the regular match. And the returned array has an additional input Property that contains the original string. In addition, there is one index Property that represents the index (starting with 0) of the matching result in the string. If the regular expression contains g Flag, the method returns an array of matching strings.
exec function   exec()
var str="hi,mynameisguoxiansheng6,33iswho?";
var zz1=/guo/g;
var n=zz1.exec(str);  //["guo"]
var zz2=/guo/;
var n1=zz2.exec(str);    //["guo",index:11,input:"hi,mynameisguoxiansheng6,33iswho?"]
n1.index    //11
n1.input    //hi,mynameisguoxiansheng6,33iswho?
exec()The function is called on a regular to pass string parameters
 As above, return the first string that matches successfully. If the matching fails, return null. 
  Search function  search()
      var str = "hi,mynameisguoxiansheng6,33iswho?";
var zz1 = /guo/;
var n = str.search(zz1);    //11
 Perform regular match lookup. If the search is successful, the matching index value in the string is returned. Otherwise return -1

7. String concat()

Splice directly with plus sign
Concat function concat()
var str1="Hello";
var str2=" world,";
var str3="Hello";
var str4="guoxiansheng";
var newStr=str1.concat(str2+str3+" "+str4);    //Hello world,Hello guoxiansheng
concat()Function can have multiple parameters, pass multiple strings, and splice multiple strings.

8. Cut and extract string (slice)

//First, slice() function:
var str="hello world!";
var n1=str.slice(-3);    //ld!
var n2=str.slice(-3,-1);    //ld
var n3=str.slice(3);    //lo world!
var n4=str.slice(3,7);    //lo w
slice() It can be a negative number. If the starting position is a negative number, find the corresponding digit forward from the last bit of the string and take the ending position backward. If it is a positive integer, take the starting position to the ending position from the front to the back.

//Second: substring() function:
var str="hello world!";
var n1=str.substring(3);    //lo world!
var n2=str.substring(3,7);    //lo w
substring()Only non negative integers can be used. The start and end positions of interception are the same slice()Function consistency.

//Third: substr() function:
var str="hello world!";
var n1=str.substr(3);    //lo world!
var n2=str.substr(3,7);    //lo wo
substr()Different from the first and second functions, it is intercepted from the start position and the end position is the maximum length of the string intercepted by the second parameter.
When the second parameter is not filled in the above three functions, the starting position is automatically intercepted to the end of the string.

9. String case conversion toLowerCase(), toUpperCase()

var mystr="Hello World!";
var lowCaseStr=mystr.toLowerCase();    //hello world!
var upCaseStr=mystr. toUpperCase();    //HELLO WORLD!

10. String de whitespace (trim)

trim Method to remove spaces before and after a string
var mystr="     hello world      ";
var trimStr=mystr.trim();    //hello world

11. String de duplication

var str="aahhgggsssjjj";
function removeRepeat(n){
var k=[];
var arr=n.split("");
for(var i=0;i<arr.length;i++){
    if(k.indexOf(arr[i])==-1){
        k.push(arr[i]);
    }
}
return k.join("");
}
removeRepeat(str);    //ahgsj

12.replace()

  • The replace() method is used to replace some characters in a string with others, or to replace a substring that matches a regular expression.
var str="abc Def!"
console.log(str.replace(/abc/, "CBA"))//CBA Def!

13.search()

  • The search() method is used to retrieve a substring specified in a string or a substring that matches a regular expression. To perform case insensitive retrieval, append the flag i. If no matching substring is found, - 1 is returned.
var str="abc DEF!"
console.log(str.search(/DEF/))//4

14.slice()

  • Extract the fragment of the string and return the extracted part in the new string.
stringObject.slice(start,end);
  • start: the starting subscript of the fragment to be extracted. If it 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 penultimate character, and so on.
  • End: the subscript immediately following the end of the fragment to be extracted. 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 parameter is negative, it specifies the position from the end of the string.
var str="abc def ghk"
console.log(str.slice(6))//f ghk

15.substr()

Extracts the specified number of characters from the string from the starting index number.
stringObject.substr(start,length).
start: 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.

var str="abc def"
console.log(str.substr(2))//c def
console.log(str.substr(2,4))// c de

16.substring()

Extracts the character between two specified index numbers in a string.
stringObject.substring(start,stop).
start: required. A nonnegative integer that specifies the position of the first character of the substring to be extracted in the stringObject.
stop: optional. A nonnegative integer, 1 more than the position of the last character of the substring to be extracted in the stringObject. If this parameter is omitted, the returned substring will continue to the end of the string.

var str="abc def"
console.log(str.substring(2))//c def
console.log(str.substring(2,4))// c

The same point: if you just write a parameter, the functions of both are the same: they are the string fragments that intercept the string from the current subscript to the end of the string.

substr(startIndex);
substring(startIndex);
var str = '123456789';
console.log(str.substr(2));    //  "3456789"
console.log(str.substring(2)) ;//  "3456789"

Difference: second parameter
substr (startIndex,lenth): the second parameter is the length of the intercepted string (intercepting a string of a certain length from the starting point);
substring (startIndex, endIndex): the second parameter is to intercept the final subscript of the string (intercept the string between two positions, 'including head and not including tail').

console.log("123456789".substr(2,5));    //  "34567"
console.log("123456789".substring(2,5)) ;//  "345"

17.codePointAt()

let s = '?a';
s.codePointAt(0) // 134071
s.codePointAt(1) // 57271
s.codePointAt(2) // 97

The parameter of codePointAt method is the position of the character in the string (starting from 0). In the above code, JavaScript regards "? A" as three characters. The codePointAt method correctly recognizes "?" on the first character and returns its decimal code point 134071 (i.e. 20BB7 in hexadecimal). On the second character (i.e. the last two bytes of "?) and the third character" a ", the result of the codePointAt method is the same as that of the charCodeAt method.

18.String.fromCodePoint()

ES5 provides the String.fromCharCode method to return the corresponding characters from the code point, but this method cannot recognize 32-bit UTF-16 characters (Unicode number is greater than 0xFFFF).

String.fromCharCode(0x20BB7)
// "ஷ"
In the above code, String.fromCharCode cannot recognize code points larger than 0xFFFF, so 0x20BB7 overflows, the highest bit 2 is discarded, and finally the character corresponding to code point U+0BB7 is returned instead of the character corresponding to code point U+20BB7.
ES6 provides the String.fromCodePoint method, which can recognize characters greater than 0xFFFF, making up for the deficiency of the String.fromCharCode method. In effect, it is just the opposite of the codePointAt method.

String.fromCodePoint(0x20BB7)
// "?"
String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y'
// true

19. String traverser interface for of

for (let codePoint of 'abc') {
  console.log(codePoint)
}
// "a"
// "b"
// "c"
In addition to traversing the string, the biggest advantage of this traverser is that it can recognize greater than 0 xFFFF Code point, traditional for The loop cannot recognize such code points.

20.at()

The at method can recognize characters with Unicode number greater than 0xFFFF and return the correct characters.

'abc'.at(0)//"a"
'luck'.at(0)//"Ji"

21.normalize()

Many European languages have intonation symbols and accents. Unicode provides two ways to represent them. One is to provide accented characters directly, such as Ǒ (u01D1). The other is to provide combining character s, that is, the combination of original characters and accents. Two characters are combined into one character, such as O (u004F) and ˇ (u030C) synthesis Ǒ (u004Fu030C).

These two representations are visually and semantically equivalent, but JavaScript cannot recognize them.

'\u01D1'==='\u004F\u030C' //false
'\u01D1'.length // 1
'\u004F\u030C'.length // 2

The above code shows that JavaScript treats synthetic characters as two characters, resulting in unequal representation between the two methods.
ES6 provides the normalize() method of string instances to unify different representation methods of characters into the same form, which is called Unicode normalization.

'\u01D1'.normalize() === '\u004F\u030C'.normalize()
// true

22.includes(), startsWith(), endsWith()

Traditionally, JavaScript has only the indexOf method, which can be used to determine whether a string is contained in another string. ES6 provides three new methods.

includes(): returns a Boolean value indicating whether a parameter string was found.
startsWith(): returns a Boolean value indicating whether the parameter string is at the head of the original string.
endsWith(): returns a Boolean value indicating whether the parameter string is at the end of the original string.

let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true

All three methods support the second parameter, which indicates where to start the search.

let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

The above code shows that the behavior of endsWith is different from the other two methods when the second parameter n is used. It targets the first n characters, while the other two methods target from the nth position to the end of the string.

23.repeat()

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

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

If the parameter is decimal, it will be rounded.

'na'.repeat(2.9) // "nana"

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

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

24.padStart(),padEnd()

ES2017 introduces the function of string completion length. If a string is not long enough, it will be completed at the head or tail. padStart() is used for head completion and padEnd() is used for tail completion.

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

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

In the above code, padStart and padEnd accept two parameters. The first parameter is used to specify the minimum length of the string, and the second parameter is used to complete the string.
If the length of the original string is equal to or greater than the specified minimum length, the original string is returned.

'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'

If the sum of the length of the complement string and the original string exceeds the specified minimum length, the complement string exceeding the number of bits will be truncated.

'abc'.padStart(10, '0123456789')
// '0123456abc'

If the second parameter is omitted, the default is to use spaces to complete the length.

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

A common use of padStart is to specify the number of digits for numeric completion. The following code generates a 10 bit numeric string.

'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"

Another use is prompt string format.

'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

25.matchAll()

The matchAll method returns all matches of a regular expression in the current string.

26. Template string

The template string is an enhanced version of the string, which is identified by backquotes (`). It can be used as an ordinary string, can also be used to define a multi line string, or embed variables in the string----- String template, which is often used in work.

// Normal string
`In JavaScript '\n' is a line-feed.`

// Multiline string
`In JavaScript this is
 not legal.`

console.log(`string text line 1
string text line 2`);

// Embedded variable in string
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

The template strings in the above code are represented by backquotes. If you need to use backquotes in the template string, you should escape it with a backslash.

let greeting = `\`Yo\` World!`;

If you use a template string to represent a multiline string, all spaces and indents are retained in the output.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);

In the above code, the spaces and newlines of all template strings are reserved. For example, there will be a newline in front of the < UL > tag. If you don't want this newline, you can use the trim method to eliminate it.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`.trim());

Variables are embedded in the template string, and the variable name needs to be written in ${}.

function authorize(user, action) {
  if (!user.hasPrivilege(action)) {
    throw new Error(
      // The traditional way of writing is
      // 'User '
      // + user.name
      // + ' is not authorized to do '
      // + action
      // + '.'
      `User ${user.name} is not authorized to do ${action}.`);
  }
}

Arbitrary JavaScript expressions can be placed inside braces, which can perform operations and reference object properties.

let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"

Functions can also be called in the template string.

function fn() {
  return "Hello World";
}
`foo ${fn()} bar`
// foo Hello World bar

If the value in braces is not a string, it will be converted to a string according to the general rules. For example, if there is an object in braces, the toString method of the object will be called by default.
If the variable in the template string is not declared, an error will be reported.

// The variable place is not declared
let msg = `Hello, ${place}`;
// report errors

Because the inside of the braces of the template string is to execute JavaScript code, if the inside of the braces is a string, it will be output as it is.

`Hello ${'World'}`
// "Hello World"

Template strings can even be nested.

const tmpl = addrs => `
  <table>
  ${addrs.map(addr => `
    <tr><td>${addr.first}</td></tr>
    <tr><td>${addr.last}</td></tr>
  `).join('')}
  </table>
`;

Posted by dirkbonenkamp on Wed, 20 Oct 2021 18:58:59 -0700