vue (javaScript) common methods for operating strings

1. Get the string length

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

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

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

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.
(1)charAt()

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

string.charAt(index)

index represents the index value of the character in the string:

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

Strings can also directly obtain corresponding characters through index values. So what is the difference between it and charAt()?

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 will return 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

3. Retrieve whether a string contains a specific sequence

1)indexOf()

indexOf(): Search for a certain character, and return the first matched position if found , otherwise -1 will be returned. The syntax is as follows:

string.indexOf(searchvalue,fromindex)

This method has two parameters:

  • searchvalue: required, specifies the string value to be retrieved;
  • fromindex: Optional integer parameter that specifies the position in the string to start searching. Its legal 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(): Search for a certain character, if found, return the last matched position, 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 search order is different. indexOf() is a forward search, and lastIndexOf() is a reverse search.

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

string.includes(searchvalue, start)

This method has two parameters:

  • searchvalue: required, the string to be found;
  • start: optional, set the position to start searching from, 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 substring passed in 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 be searched;
  • 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

As you can see, when the second parameter is set to 5, it will be retrieved from the first 5 characters of the string, so true will be returned.

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:

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

The parameters string1, string2, ..., stringX are required, and they will be concatenated into one or more string objects of a string.

let str = "abc";
console.log(str.concat("efg"));          //输出结果:"abcefg"
console.log(str.concat("efg","hijk")); //输出结果:"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. 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.
let str = "abcdef";
str.split("c");    // 输出结果:["ab", "def"]
str.split("", 4)   // 输出结果:['a', 'b', 'c', 'd'] 

If an empty string is used as a 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, you can split multiple delimiters at the same time, which can be achieved using regular expressions:

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

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:

string.slice(start,end)

This method has two parameters:

  • start: required. The starting index of the fragment to be intercepted, the first character position is 0. If it is a negative number, it is intercepted from the end.
  • end: optional. The index 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 starting 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 a specified number of characters starting from the start subscript in a string. Its syntax is as follows:

string.substr(start,length)

This method has two parameters:

  • start is required. The starting index of the substring to be extracted. Must be a numeric value. If negative, this 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 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, the string from the beginning to the end of stringObject is returned.
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 that specifies the position in string of the first character of the substring to be extracted.
  • to: optional. A non-negative integer that is one more position in the string than the last character of the substring to be extracted. If this parameter is omitted, the returned substring will go to the end of the string.

Note: If the parameters from and to are equal, then this 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, the string will be returned.

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"

7. String case conversion

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 uppercase the first letter in 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 that specifies the substring or pattern to be replaced. If the value is a string, it is retrieved as a literal text pattern rather than first being converted to a RegExp object.
  • newvalue: required. A string value. Specifies functions for replacing text or generating replacement text.
let str = "abcdef";
str.replace("c", "z") // 输出结果:abzdef

Perform a global replacement, 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 only replaces the first matching substring.

(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:

string.match(regexp)

The method's required parameter regexp is a RegExp object that specifies the pattern to be matched. 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 storing the 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()

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:

string.search(searchvalue)

The parameter regex of this method can be the substring that needs to be retrieved in the string, or it can be the RegExp object that needs to be retrieved.

Note: To perform a case-ignoring 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. If no matching substring is found, -1 is returned.

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

let str = "abcdef";
str.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:

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

10. 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 a negative number or Infinity, an error will be reported:

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

If the argument is a decimal between 0 and -1, it is equivalent to 0 because rounding is performed first. A decimal between 0 and -1 is equal to -0 after rounding, and repeats are regarded as 0.

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

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

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

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

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

The above are the commonly used string methods, welcome to add more

Guess you like

Origin blog.csdn.net/2301_77456141/article/details/134171047