js string function

Posted by sweyhrich on Wed, 17 Nov 2021 17:07:38 +0100

Definition of string

Conventional methods' 'and ` ` are OK

// 1:  To define a string using a pair of single quotes or a pair of double quotes
let str1 = "str1"
console.log(str1) // str1
let str2 = 'str2'
console.log(str2) // str2
// 1. In JavaScript, there is no essential difference between strings defined in double quotation marks and strings defined in single quotation marks
// 2. Both single quotation marks and double quotation marks must be used in pairs. One single quotation mark and double quotation mark cannot be paired
let str3 = "str3'"
console.log(str3) //str'
// 3. Single quotation marks cannot appear in the string in single quotation marks, but double quotation marks can appear
//    Double quotation marks cannot appear in a string in double quotation marks. Single quotation marks can appear
// 4. When defining a string in single quotation marks and double quotation marks, it must be completed in one line and cannot be wrapped

// 2:  Use template strings to define strings: we can use a pair of backquotes to define strings (the ` ` above the tab key)
let str4 = `This is an ordinary string`
let str5 = `This is a new line 
character string`
let str6 = 7
let str7 = 6
// Template Strings use variables with ${}
let str8 = `This is a string that can parse variables, for example: ${str6 + str7}`
console.log(str4) // This is an ordinary string
console.log(str5) /* This is a new line 
character string */
console.log(str6) // 7
console.log(str7) // 6
console.log(str8) // This is a string that can parse variables, for example: 13
// ${varName} or ${value}. That is, ${} can be a variable name or a literal value (such as ${123} or ${asd}).

Don't care what the content is, only match the corresponding "" ` ` and escape character

let str1 = "true";  //Convert Boolean values to strings
let str2 = "123";  //Converts a numeric value to a string
let str3 = "[1,2,3]";  //Convert array to string
let str4 = "{x : 1; y : 2}";  //Convert object to string
let str5 = "console.log('Hello,World')";  //Converts an executable expression to a string
// true
// 123
// [1,2,3]
// {x : 1; y : 2}
// console.log('Hello,World')
console.log(typeof str1)
console.log(typeof str2)
console.log(typeof str3)
console.log(typeof str4)
console.log(typeof str5)
// string
// string
// string
// string
// string

Escape character:\

// When defining a string, some special characters are not suitable for direct appearance. For example: newline character, single quotation mark (cannot appear in single quotation mark), double quotation mark (cannot appear in double quotation mark)

For example, the following is wrong

let str = " " " 
// Syntax errors will be reported directly

However, we need to use it in this way. At this time, we need to use the \ escape character, for example:

// The \ n is used here to represent the newline character
// Here \ "is used to represent double quotation marks.
let str1 = 'This is a new line\n character string'
let str2 = 'This is a new line\' character string'
/* This is a new line
 character string */
// This is a newline 'string
let str3 = `123 
str3 \"\'`
// If you define a string as a template string, you can directly use carriage return to wrap the line. However, if you want to use backquotes in it, you must also escape
// 123
// str3 "'

Properties of String object

The string can be regarded as an array composed of characters. It has the length of the attribute length ----- -- > string, which can be traversed through the for loop

let  str = 'abcd'
for(let i of str){
// a
// b
// c
// d

String property: immutable. The value of the string cannot be changed

Method of String object


Here is one thing to explain first: character comparison refers to the operation of comparing the size of a single character or string in dictionary order. Generally, the size of ASCII code value is used as the standard for character comparison.

When comparing JS strings greater than (less than), they will be compared according to the ASCII value code of the first different character

Here are some examples

let a="91";                   
let b="390"                    
console.log(a.charCodeAt())    // 57
console.log(b.charCodeAt())    // 51
console.log(a<b)               // false

"91" < "390" the resu lt is false

When comparing strings, they will be converted into ascll printed characters (9 is 57, 3 is 51). Characters will be compared in turn. If the first character is equal, the next character will be compared or '\ 0' will be encountered. Therefore, during comparison, they must be converted into number for comparison

So explain the above results

The first character in a is 9 and the first character in B is 3. They are different, so start comparing their ascll. The acsll (57) of a is greater than the acsll (51) of a, so the resu lt of "91" < "390" is false

let a = 34
let b = "34"
console.log( a == b ) //true

If one is a string and the other is a numeric value, you tend to convert the string to a numeric value and compare it

Let's get to the point

Because the browser support for the latter parameter is not very friendly, I won't introduce it more. If you are interested, you can see it on MDN.

The general usage is a.localeCompare(b). Browsers basically support it.

let str1 = "123456"
let str2 = "1234567"
let str3 = "12345678"
let str4 = "123478"
let str5 = "abcd"
let str6 = "dcba"
// Return value greater than 0: indicates that the current string is greater than the comparison string targetString
// Return value less than 0: indicates that the current string is less than the comparison string targetString
// Return value equal to 0: indicates that the current string is equal to the comparison string targetString
console.log(str1.localeCompare(str2)); // -1
console.log(str2.localeCompare(str2)); // 0
console.log(str3.localeCompare(str2)); // 1
console.log(str4.localeCompare(str2)); // 1
console.log(str5.localeCompare(str6)); // -1


be careful:

  1. The index of the string is from 0 to length-1
  2. slice(start, end)
  3. substring(start, to)
  4. substr (start, length) differs from the first two in that the second parameter is length
  5. The difference between the three is very fine. Please take a closer look at the following case results
// slice(start,end)
// Intercept the string from the start index position to the string before the end index position
// The first character position in the start parameter string is 0, the second character position is 1, and so on. If it is a negative number, it indicates how many strings are intercepted from the tail, and slice(-2) indicates that the penultimate element in the original array is extracted to the last element (including the last element).
// If the end parameter is negative, - 1 refers to the position of the last character of the string, - 2 refers to the penultimate character, and so on.
let str1 = "123456789"
console.log(str1.slice(0, str1.length))
// 123456789
let str2 = "123456789"
console.log(str2.slice(1, 3))
// 23
// 89
// Using slice() the original array will not change
// 123456789
// When the parameter is negative, the processing string starts at the end
// 12345678
console.log(str1.slice(6, -5))
console.log(str1.slice(3, -5))
// 4


// substr(start,length)
// Starting from the start index bit, intercept the string with length. If there is no length, intercept all subsequent strings
let str = "str1"
// Yes, yes, the final result is an empty string
// tr1
// tr


// substring(start,to)
let str = "str1"
// If the parameters start and end are equal, the method returns an empty string (that is, a string of length 0).
// Start = > to if the value of start is greater than the position of to, it can be understood as reversing the position of the two parameters
// str1
// t
// tr
// t
// r1


// Returns the Unicode encoding of the index position of the string
// 97
// 98


// charAt(index)
// Returns the character at the specified position (index).
// If index is less than 0 or greater than or equal to the length of string string.length, it returns an empty string.
let str = "str1"
// t


console.log(String.fromCharCode( 5, 66, 67, 68, 69, 70, 71 ))
console.log(String.fromCharCode( 38 ))
console.log(String.fromCharCode( 13, 22269 ))
// &
// country


// concat()
// General string splicing can directly use + connection
console.log("c".concat("23", "str"));
// c23str


// indexOf(searchString,position)
let str1= "123qwe"
// 1
// -1
// -1
// -1
// 4
// -1


// lastIndexOf(searchString,position)
let str1= "123qwe"
// It is similar to the indexOf method, except that it starts at the end of the string, not at the beginning.
// 1
// -1
// -1
// -1
// 4
// 4


let str1 = "121416"
let str2 = "1234567"
// Only the first matching character will be replaced
// 123456721416
var stringObj="Eternal people";
var newstr=stringObj.replace("Last forever","China"); 
// China, the people of all ages

You will find that the second typo "end of ancient times" has not been replaced by "China"

var reg=new RegExp("Last forever","g"); //Create regular RegExp object
var stringObj="Eternal people";
var newstr=stringObj.replace(reg,"China"); 
// China, Chinese people


let str1 = "thorough Vue At the bottom, write one vuex\n 348\n"
// split() will split the string with the passed parameters and finally return an array
console.log(str1.split(" "))
// ['deep', 'Vue bottom layer, handwriting a vuex\n', '348\n']
// ['go deep into the bottom of Vue and write a vuex', '348', '']


// Returns a Boolean value indicating whether a parameter string was found.
let str = 'This is the test string';
if (str.indexOf('test') !== -1) {
  console.log(true)    //contain
} else {
  console.log(false)    //Not included
// true


// Returns a Boolean value indicating whether the parameter string is at the head of the original string.
let str = 'This is the test string';
if (str.startsWith('this') === true) {
} else {
if (str.startsWith('yes') === true) {
} else {
// true
// false


// Returns a Boolean value indicating whether the parameter string is at the end of the original string.
let str = 'This is the test string';
if (str.endsWith('this') === true) {
} else {
if (str.endsWith('strand') === true) {
} else {
// false
// true
  • The three methods include() startswith() endswith() all support the second parameter, which indicates the location where to start the search. If the parameter of repeat is negative or Infinity, an error will be reported.


// The repeat method returns a new string, indicating that the original string is repeated n times. If the parameter is decimal, it will be rounded.
let str = 'This is the test string';
// This is the test string this is the test string this is the test string

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.
console.log('x'.padStart(5, 'ab')) // 'ababx'
console.log('x'.padStart(4, 'ab')) // 'abax'
console.log('x'.padEnd(5, 'ab')) // 'xabab'
console.log('x'.padEnd(4, 'ab')) // 'xaba'
// If the length of the original string is equal to or greater than the maximum length, the string completion will not take effect and the original string will be returned

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

// A common use of padStart() is to specify the number of digits for numeric completion. The following code generates a 10 bit numeric string.
console.log('1'.padStart(10, '0')) 
console.log('12'.padStart(10, '0')) 
console.log('123456'.padStart(10, '0')) 
// 0000000001
// 0000000012
// 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"


  • ES2019 adds trimStart() and trimEnd() methods to string instances. Their behavior is consistent with trim(), trimStart() eliminates spaces at the beginning of the string, and trimEnd() eliminates spaces at the end. They return a new string and do not modify the original string.
const s = '  abc  ';
s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"


The search() method is used to retrieve a substring specified in a string or a substring that matches a regular expression.
If no matching substring is found, - 1 is returned.

The search() method is case sensitive when searching.

let str = "abcd Abcd abc"
// 0
// 5

Match (regular expression)

let article = "12345657abcdeABCDE123"
// [ '123', index: 0, input: '12345657abcdeABCDE', groups: undefined ]
// [ '3', index: 2, input: '12345657abcdeABCDE123', groups: undefined ]

toLowerCase() ,toUpperCase()

let article = "this is pink"
// this is pink

Topics: Javascript Front-end ECMAScript