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
console.log(str1)
let str2 = "123";  //Converts a numeric value to a string
console.log(str2)
let str3 = "[1,2,3]";  //Convert array to string
console.log(str3)
let str4 = "{x : 1; y : 2}";  //Convert object to string
console.log(str4)
let str5 = "console.log('Hello,World')";  //Converts an executable expression to a string
console.log(str5)
// 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'
console.log(str1)
console.log(str2)
/* 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
console.log(str3)
// 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){
  console.log(i)
}
// a
// b
// c
// d

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

Method of String object

localeCompare()

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

slice()

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
console.log(str2.slice(-2))
// 89
// Using slice() the original array will not change
console.log(str2)
// 123456789
console.log(str1.slice(0,-1))
// 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()

// 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"
console.log(str.substr(1))
console.log(str.substr(1,2))
// Yes, yes, the final result is an empty string
console.log(str.substr(1,-1))
// tr1
// tr
// 

substring()

// substring(start,to)
let str = "str1"
console.log(str.substring(0))
console.log(str.substring(1,2))
// If the parameters start and end are equal, the method returns an empty string (that is, a string of length 0).
console.log(str.substring(1,1))
// 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
console.log(str.substring(3,1))
console.log(str.substring(2,1))
console.log(str.substring(4,2))
// str1
// t
//
// tr
// t
// r1

charCodeAt()

// Returns the Unicode encoding of the index position of the string
console.log("a".charCodeAt(0))
console.log("aabb".charCodeAt(2))
// 97
// 98

charAt()

// 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"
console.log(str.charAt(1))
console.log(str.charAt(5))
// t
// 

String.fromCharCode()

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

concat()

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

indexOf()

// indexOf(searchString,position)
let str1= "123qwe"
console.log(str1.indexOf("2"))
console.log(str1.indexOf("a"))
console.log(str1.indexOf("ad"))
console.log(str1.indexOf("ae"))
console.log(str1.indexOf("we"))
console.log(str1.indexOf("we",5))
// 1
// -1
// -1
// -1
// 4
// -1

lastIndexOf()

// 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.
console.log(str1.lastIndexOf("2"))
console.log(str1.lastIndexOf("a"))
console.log(str1.lastIndexOf("ad"))
console.log(str1.lastIndexOf("ae"))
console.log(str1.lastIndexOf("we"))
console.log(str1.lastIndexOf("we",5))
// 1
// -1
// -1
// -1
// 4
// 4

replace()

let str1 = "121416"
let str2 = "1234567"
// Only the first matching character will be replaced
console.log(str1.replace("1",str2))
// 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

split()

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']
console.log(str1.split("\n"))
// ['go deep into the bottom of Vue and write a vuex', '348', '']

includes()

// 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

startsWith()

// 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) {
  console.log(true)
} else {
  console.log(false)
}
if (str.startsWith('yes') === true) {
  console.log(true)
} else {
  console.log(false)
}
// true
// false

endsWith()

// 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) {
  console.log(true)
} else {
  console.log(false)
}
if (str.endsWith('strand') === true) {
  console.log(true)
} else {
  console.log(false)
}
// 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.

repeat()

// 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';
console.log(str.repeat(3));
// 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"

trimStart(),trimEnd()

  • 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"

search()

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"
console.log(str.search("abc"))
// 0
console.log(str.search("Abc"))
// 5

Match (regular expression)

let article = "12345657abcdeABCDE123"
console.log(article.match("123"));
// [ '123', index: 0, input: '12345657abcdeABCDE', groups: undefined ]
console.log(article.match("3"));
// [ '3', index: 2, input: '12345657abcdeABCDE123', groups: undefined ]

toLowerCase() ,toUpperCase()

let article = "this is pink"
console.log(article.toLowerCase())
console.log(article.toUpperCase())
// this is pink
// THIS IS PINK

Topics: Javascript Front-end ECMAScript