preface
In front-end development, we work with strings on a daily basis, so we need to study the properties and methods of String and String.prototype.
We can use the Object. GetOwnPropertyNames () method to look at the String and String. What are the properties and methods: the prototype
New additions to ES5 include:
- trim
New additions to ES6 include:
- String. FromCodePoint (), String. Raw ()
- CodePointAt, Normalize, includes, startsWith, endsWith, repeat, padStart, padEnd, trimStart, trimEnd, matchAll, replaceAll
Before I look at these methods, let’s take a quick look at regular expressions:
Regular expression
Regular expressions: Regular expressions, also known as rules, enable computers to read human rules
Using regular expressions is a good way to represent strings
- Both ends of a regular expression
/
Separate, as:/ Regular expression /
- Add to the regular expression
g
According to global,The global matching - add
i
Indicates ignore, which ignores string case - add
m
Represents a mutiple, allowing multiple lines to match
Match rule
character | describe | example |
---|---|---|
Any character x | Match this character | /a/.test(str) Check whether STR contains the letter A |
x l y | Match x or y | /alb/.test(str) Check whether STR contains the letter A or B |
[xyz] | Collection of characters. Matches any of x, y, or z | /aeiou/ Matches all vowels |
[a-z] | Character range. Match lowercase letters | /[a-z]/.test(str) Checks whether STR contains lowercase letters |
[0-9] | Character range. Matching numeric character | /[0-9]/.test(str) Determines whether STR contains alphanumeric characters |
[A-Z] | Character range. Match uppercase letters | /[A-Z]/.test(str) Determines whether STR contains uppercase letters |
[A-Za-z0-9] | Character range. Matches any English character and numeric character | /[A-Za-z0-9]/.test(str) Checks whether STR contains alphanumeric characters |
[^ 0-9] | Invert the character range. Matches any character outside the specified range,^ Is placed on[] The inside of the |
/[^a-z]/.test(str) Determines whether STR contains characters other than numeric characters |
^ | Matches the input stringstartlocation | ^ab Matches a string beginning with ab |
$ | Matches the input stringThe end of thelocation | ab$ Matches a string ending in ab |
^… $ | Matches the input stringThe end of thelocation | ^\d$ Means to matchaThe number of [0-9] |
* | Matches the previous subexpressionzeroOr more | zo* Can matchz orzoo(o..) But it doesn’t matchzo |
+ | Matches the previous subexpressionAt a timeOr more | zo* Can matchzo orzoo(o..) But it doesn’t matchz |
? | Matches the previous subexpressionzeroorAt a time | zo* Can matchz orzo But it doesn’t matchzoo(o..) |
\d | Equivalent to [0-9] | ^\d+$ Means to matchmultipleThe number of [0-9] |
\D | Equivalent to [^ 0-9] | |
\w | Equivalent to [A-za-z0-9_], which includes the underscore_ |
|
\W | Equivalent to [^ A Za – z0-9 _] |
Creating a string
var str = "hello,world!"
var str = new Array("hello,world!") [0]
Copy the code
Accessing characters in a string
To access an item of a string:
- Direct use of
[index]
indexing
var str = "hello,world!"
str[0] // "h"
str[5] / / ","
str[12] // undefined
Copy the code
str.charAt( index )
- use
str.charAt( index )
Method can also access the character of the specified index of the string
var str = "hello,world!"
str.charAt(0) // "h"
str.charAt(5) / / ","
str.charAt(12) // undefined
Copy the code
Modify string
Modify one or more substrings of a string:
- Note: Direct use
[index]
Index change isIs not workablethe
var str = "hello,world!"
str[4] = "g" // "g"
str // "hello,world!"
Copy the code
There are three solutions:
str.replace( searchValue , replaceValue / replacer)
- Direct use of
str.replace()
Method, but the scenario is what string is already being replaced, not the index at which it is being replaced
var str = "hello,world!"
str.replace("o"."g") // "hellg,world!"
Copy the code
- use
str.split()
After converting the string to an array, replace one of the items in the array, and then usearr.join()
The disadvantage of converting an array back to a stringWaste of space
var MyReplace = function(str,index,s){
var arr = str.split("")
arr[index] = s
return arr.join("")}var str = "hello,world!"
MyReplace(str,4."g") // "hellg,world!"
Copy the code
- Copy substring and concatenate
var MyReplace = function(str,index,s){
return str.substring(0,index) + s + str.substring(index + 1)}var str = "hello,world!"
MyReplace(str,4."g") // "hellg,world!"
Copy the code
Str.replace (/ regular expression /, replaceValue/replacer)
var str = "hello,world!"
str.replace(/o/g."g") // "hellg,wgrld!"
Copy the code
In addition, global substitution can be achieved using the str.replaceall () method
str.replaceAll( searchValue, replaceValue / replacer)
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy? ';
console.log(p.replaceAll('dog'.'monkey'));
// "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
Copy the code
str.trim()
Function: Removes whitespace characters from both ends of a string
var str = ' Hello world! ';
console.log(str); // " Hello world! ";
console.log(str.trim()); // "Hello world!" ;
Copy the code
String splicing
- Use + sign concatenation directly
"h" + "e" // "he"
Copy the code
String.raw
Let’s take a look at what template strings are before we learn how to do this
Template string
${} = ${}; ${} = ${}; ${}; This is also one of the functions of String.raw (so you don’t have to write String.raw in this section)
${} can be an expression or a string
String. The use of raw
You usually don’t need to think of it as a normal function, you just put it in front of the template string, rather than calling it with parentheses and a bunch of arguments, and the engine will call it for you
String.raw`Hi\nThe ${2+3}! `; // 'Hi\n5! ', the character after Hi is not a newline character, \ and n are two different characters
String.raw `Hi\u000A! `; // Any type of escape will fail, leaving output as is
let name = "Bob";
String.raw `Hi\n${name}! `; // "Hi\nBob!" , and the interpolation expression will work fine
Copy the code
String.raw can take multiple arguments. The first is an object, where a field is called RAW and the value of the field is an array, and the other arguments are inserted between two elements of the array
/ / the following functions and ` foo ${2 + 3} bar ${' Java '+' Script '} baz ` is equal.
String.raw({
raw: ['foo'.'bar'.'baz']},2 + 3.'Java' + 'Script'); // 'foo5barJavaScriptbaz'
Copy the code
str.concat( s1 , [s2,s3,…] )
Function: Merge one or more strings with the original string concatenation to form a new string and return
Note: If the merged element is not a string, the toString method is called to convert it to a string first
var str = 'Hello, '
console.log(str.concat('Kevin'.'. Have a nice day.')) // Hello, Kevin. Have a nice day.
var arr = ['Hello'.' '.'Venkat'.'! ']
"".concat(... arr)// "Hello Venkat!" , using the rest parameter as a shorthand notation
"".concat({}) // [object Object]
"".concat([]) / / ""
"".concat(null) // "null"
Copy the code
str.padEnd( targetLength , [padString] )
Function: Fills the current string with a string (or repeats if necessary), returning the string that has been filled to a specified length. Populate from the end of the current string (right)
Parameters:
- The target length to which the current string needs to be filled
- Fill string
var str1 = '200';
console.log(str1.padEnd(5)); / / "200"
var str2 = 'Overflow part of string due to lack of space, replace overflow part with ellipsis';
console.log(str2.padEnd(28.'. ')); // "Overflow part of string due to space shortage, replace overflow part with ellipsis..."
Copy the code
str.padStart()
Function: Fills the current string with another string (repeated many times if necessary) so that the resulting string reaches a given length. Starts from the left side of the current string
var str1 = '5';
console.log(str1.padStart(2.'0')); // "05"
var fullNumber = '2034399002125581';
var last4Digits = fullNumber.slice(-4);
var maskedNumber = last4Digits.padStart(fullNumber.length, The '*');
console.log(maskedNumber); / / "* * * * * * * * * * * * 5581"
Copy the code
Retrieve substrings
str.includes( “searchstr” , [start] )
Searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr: searchstr
var str = "hello,world!"
str.includes("o") // true
str.includes("6") // false
str.includes('Hello'); // false, this method is case sensitive
Copy the code
str.indexOf( “searchstr” , [start] )
Function: The indexOf method should be an upgraded version of includes. The index of the first occurrence of the target string searchstr in the original string STR, starting at index start, or -1 if not found
var str = "hello,world!"
str.indexOf("o") / / 4
str.indexOf("6") // -1
Copy the code
str.lastIndexOf( “searchstr” , [start] )
Function: The index of the last occurrence of the target string searchstr in STR (the first character of searchstr corresponds to the index in STR), starting at the index start, or -1 if not found
var str = "hello,world!"
str.indexOf("o") / / 7
str.lastIndexOf("6") // -1
Copy the code
Str.search (/ regular expression /)
Note: If a non-regular expression object regEXP is passed in, it is implicitly converted to a regular expression object using new RegEXP (regEXP)
Function: Performs a search match between a regular expression and a String. Returns the index of the first match of the regular expression in the string; Otherwise -1 is returned
// For example, it is used to check whether the string contains pure numbers and non-numeric characters
var str1 = "8642813359942"
var str2 = "36455f912h338"
str1.search(/[^0-9]/g) Str1 is a string of numeric characters
str2.search(/[^0-9]/g) Str2 contains non-numeric characters and the index of the first non-numeric character is 5
Copy the code
Str.match (/ regular expression /)
Function: Returns the result of a string matching a regular expression, returns an array of matching characters, or returns null if there is no matching result
var str = 'The quick brown fox jumps over the lazy dog. It barked.';
str.match(/[A-Z]/g); // ["T", "I"]
str.match(/[0-9]/g); // null
Copy the code
Str.matchall (/ regular expression /)
Function: Returns an iterator containing the results of all matching regular expressions and a grouping capture group
var str = 'test1test2';
var arr = [...str.matchAll(/t(e)(st(\d?) )/g)];
Copy the code
Interconversion between strings and arrays
arr = str.split()
- If no argument is passed, an array with only one element of the string is returned
- If an empty string is passed in, the string is unpacked, character by character, into the array, and the array is returned
- If a non-empty string is passed in as an argument, but the string does not contain the non-empty string, an array with only one element of the string is returned
- If the passed parameter is a non-empty string and the string contains the non-empty string, the string is divided into multiple substrings and put into an array with the same order. Finally, the array is returned
var str = "hello,world!"
str.split() // ["hello,world!"]
str.split("") // ["h", "e", "l", "l", "o", ",", "w", "o", "r", "l", "d", "!"]
str.split("6") // ["hello,world!"]
str.split(",") // ["hello" , "world!"]
Copy the code
Simple code implementation API:
var MySplit = function(){
if(arguments.length === 1) return MySplit1(arguments[0])
else if(arguments.length === 2) return MySplit2(arguments[0].arguments[1])
else console.log("Parameter input format is incorrect")}var MySplit1 = function(str){ // Only one argument is passed
return [str]
}
var MySplit2 = function(str,s){ // Two arguments are passed in
if(str.length === 0) return [""]
var arr = []
if(s === "") {for(let i in str) arr.push(str[i])
return arr
}
var len = str.length
var l = s.length
var start = 0
var end = 0
while(true) {// Use the indexOf method to search the string s, obtain the index, because the slice method cannot change the original string,
// Therefore, the indexOf method is assisted by the second argument
end = str.indexOf(s,start)
if(end === -1) {
arr.push(str.slice(start))
break
}
arr.push(str.slice(start,end))
start = end + l
}
return arr
}
Copy the code
Testing:
Here is just a simple implementation, there may be a lot of bugs, later have time to slowly fill, interested partners can implement by themselves
str = arr.join()
- If no arguments are passed, the default connection string is
.
The comma. That is to say, each element.
Returns a concatenated string for a concatenated rune - If an empty string is passed in, the array elements are used first
toString
Convert to a string and concatenate it without a hyphen - If the argument passed is a non-empty string, the non-empty string is used as the concatenation string, and the array elements are used first
toString
After converting to a string, concatenate it into a string in the same relative order
var arr = ["hell".",w"."rld!"]
arr.join() // "hell,,w,rld!"
arr.join("") // "hell,wrld!"
arr.join("o") // "hello,world!"
Copy the code
Simple code implementation API:
var MyJoin = function(){
if(arguments.length === 1) return MyJoin1(arguments[0])
else if(arguments.length === 2) return MyJoin2(arguments[0].arguments[1])
else console.log("Parameter input format is incorrect")}var MyJoin1 = function(arr){ // Only one argument is passed
return MyJoin2(arr,",")}var MyJoin2 = function(arr,s){ // Two arguments are passed in
if(str.length === 0) return ""
var res = ""
if(s === "") {for(let i in arr) res += arr[i]
return res
}
var len = arr.length
for(let i = 0; i < len; i++){ res += arr[i]if(i < len - 1) res += s
}
return res
}
MyJoin(["hell".",w"."rld!"]."")
Copy the code
Testing:
Here is just a simple implementation, there may be a lot of bugs, later have time to slowly fill, interested partners can implement by themselves
Intercept string
str.substring( start , [end] )
If [end] is omitted, [end] defaults to str.length
var str = 'hello,world! ';
str.substring(6) // "world!"
str.substring(6.8) // "wo"
Copy the code
str.slice( start , [end])
If [end] is omitted, [end] defaults to str.length; if [end] is omitted, [end] defaults to STR. If start is negative, the negative number indicates the number of digits
var str = 'hello,world! ';
str.slice(6) // "world!"
str.slice(6.8) // "wo"
Copy the code
What is the difference between str.substring and str.slice
- Two parameters passed in descending order are handled differently:
- Substring: The second parameter is smaller than the first parameter, and substring automatically returns the value
The little
As a start of - Slice: The second parameter is smaller than the first parameter, which Slice considers an error and returns an empty string
- Substring: The second parameter is smaller than the first parameter, and substring automatically returns the value
var str = 'hello,world! ';
str.substring(8.6) // "wo"
str.slice(8.6) / / ""
Copy the code
- The processing of negative parameters is different:
- Substring: will simply convert all negative arguments to 0
- Slice: Minus is the last digit
var str = 'hello,world! ';
str.substring(3, -4) // "hel"
str.slice(3, -4) // "lo,wo"
Copy the code
str.substr( start , [length] )
If [length] is omitted, the index will be truncated to the end of the string. If start is negative, the negative number indicates the number of digits
var str = 'hello,world! ';
str.substr(6) // "world!"
str.substr(6.4) // "worl"
Copy the code
Case conversion
str.toLowerCase()
str.toUpperCase()
str.toLocaleLowerCase()
str.toLocaleUpperCase()
var stringValue = "hello world";
console.log(stringValue.toLowerCase()); //"hello world"
console.log(stringValue.toUpperCase()); //"HELLO WORLD"
console.log(stringValue.toLocaleLowerCase()); //"hello world"
console.log(stringValue.toLocaleUpperCase()); //"HELLO WORLD"
Copy the code
The toLocaleLowerCase() and toLocaleUpperCase() methods are locale-specific implementations, and few languages (such as Turkish) apply special rules for Unicode case conversions, so locale-specific methods must be used to ensure proper conversions
Refer to the article
- String – JavaScript | MDN