Today I’m going to look at some JavaScript basics, but basics are really important. Also clearly remember, this year spring recruitment, a large factory interviewer mercilessly ridicule my JavaScript API can not remember 🤣 is too embarrassed, mainly with too little, so usually still want to use more accumulation. Today we are going to take a look at some common string methods in JavaScript! The article content is more, the suggestion collects again to learn first!
1. Obtain 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 // Output: 5
Copy the code
2. Get the value at the specified position in the string
Both the charAt() and charCodeAt() methods can be indexed to get a value at a given location:
- The charAt() method retrieves the character at the specified position;
- The charCodeAt() method gets the Unicode value specified as a worthy character.
(1) the charAt ()
The charAt() method returns a character at a specified position. The syntax is as follows:
string.charAt(index)
Copy the code
Index indicates the index value of a character in a string:
const str = 'hello';
str.charAt(1) // Output result: e
Copy the code
We know that strings can also be indexed to get characters directly, so what’s the difference between this and charAt()? Here’s an example:
const str = 'hello';
str.charAt(1) // Output result: e
str[1] // Output result: e
str.charAt(5) // Output result:"
str[5] // Output result: undefined
Copy the code
As you can see, STR [index] returns undefined and charAt(index) returns an empty string if index is not in the length range of STR. In addition, STR [index] is not compatible with IE6-IE8, and charAt(index) is compatible.
(2) the charCodeAt ()
CharCodeAt () : This method returns the Unicode value of the character at the specified index position, an integer between 0 and 65535, representing the UTF-16 code unit at the given index, or NaN if there are no characters at the specified position:
let str = "abcdefg";
console.log(str.charCodeAt(1)); // "b" --> 98
Copy the code
This method allows you to get characters in a string that specify a range of Unicode encoding values. For example, the Unicode encoding range for the numbers 0 to 9 is 48 to 57. This method can be used to filter the numbers in a string, although it is more convenient if you are more familiar with regular expressions.
3. Retrieve whether the string contains a particular sequence
All five methods can be used to retrieve whether a particular sequence is contained in a string. The first two methods get the index value of the specified element and only return the position of the first matched value. The last three methods return Boolean values indicating whether the specified value is matched.
Note: All 5 methods are case sensitive!
(1) the indexOf ()
IndexOf () : Searches for a character, if any, returns the position matched for the first time, otherwise returns -1.
string.indexOf(searchvalue,fromindex)
Copy the code
This method takes two parameters:
- Searchvalue: Required, specifying the string value to retrieve;
- Fromindex: An optional integer parameter specifying where to start retrieval in a string. Its legal values are 0 to String.length-1. If omitted, it is retrieved from the first character of the string.
let str = "abcdefgabc";
console.log(str.indexOf("a")); // Output: 0
console.log(str.indexOf("z")); // Output: -1
console.log(str.indexOf("c".4)) // Output: 9
Copy the code
(2) the lastIndexOf ()
LastIndexOf () : Searches for a character, returns the position of the last match if any, and -1 otherwise
let str = "abcabc";
console.log(str.lastIndexOf("a")); // Output: 3
console.log(str.lastIndexOf("z")); // Output: -1
Copy the code
This method is similar to indexOf() except that the order of the lookup is different, indexOf() is a positive lookup and lastIndexOf() is a reverse lookup.
(3) includes ()
Includes () : This method is used to determine whether a string contains a specified substring. Returns true if a matching string is found, false otherwise. The syntax for this method is as follows:
string.includes(searchvalue, start)
Copy the code
This method takes two parameters:
- Searchvalue: required, string to find;
- Start: Optional, set the search to start at that location. Default is 0.
let str = 'Hello world! ';
str.includes('o') // Output result: true
str.includes('z') // Output result: false
str.includes('e'.2) // Output result: false
Copy the code
(4) the startsWith ()
StartsWith () : this method checks if the string startsWith the specified substring. Returns true if it begins with the specified substring, false otherwise. The syntax is the same as the includes() method above.
let str = 'Hello world! ';
str.startsWith('Hello') // Output result: true
str.startsWith('Helle') // Output result: false
str.startsWith('wo'.6) // Output result: true
Copy the code
(5) the endsWith ()
EndsWith () : this method is used to determine whether the current string endsWith a specified substring. Returns true if the substring passed is at the end of the search string, false otherwise. The syntax is as follows:
string.endsWith(searchvalue, length)
Copy the code
This method takes two parameters:
- Searchvalue: Required, substring to search for;
- Length: Sets the length of the string. The default value is the original string length, string.length.
let str = 'Hello world! ';
str.endsWith('! ') // Output result: true
str.endsWith('llo') // Output result: false
str.endsWith('llo'.5) // Output result: true
Copy the code
As you can see, when the second argument is set to 5, it is retrieved from the first five characters of the string, so it returns true.
4. Concatenate multiple strings
The concat() method is used to join two or more strings. This method does not alter the original string, but returns a new string that concatenates two or more strings. The syntax is as follows:
string.concat(string1, string2, ... , stringX)Copy the code
Where parameters string1, string2… StringX is required, they will be concatenated into a string of one or more string objects.
let str = "abc";
console.log(str.concat("efg")); // Output result: "abcefg"
console.log(str.concat("efg"."hijk")); // Output result: "abcefghijk"
Copy the code
Although the concat() method is specifically used to concatenate strings, the addition operator + is used most often in development because it is simpler.
5. Split strings into arrays
The split() method splits a string into an array of strings. This method does not change the original string. The syntax is as follows:
string.split(separator,limit)
Copy the code
This method takes two parameters:
- Separator: required. A string or regular expression that splits the string from the point specified by this parameter.
- Limit: Optional. This parameter specifies the maximum length of the array to be returned. If this parameter is set, no more substrings are returned than the array specified by this parameter. If this parameter is not set, the entire string is split regardless of its length.
let str = "abcdef";
str.split("c"); ["ab", "def"]
str.split("".4) ['a', 'b', 'c', 'd']
Copy the code
If an empty string is used as separator, each character in the string is separated.
str.split(""); // Output result: ["a", "b", "c", "d", "e", "f"]
Copy the code
When splitting a string into an array, you can split multiple separators at the same time using regular expressions:
const list = "apples,bananas; cherries"
const fruits = list.split(/ [;] /)
console.log(fruits); ["apples", "bananas", "cherries"]
Copy the code
6. Intercept strings
The substr(), substring(), and slice() methods can all be used to intercept strings.
(1) the slice ()
The slice() method is used to extract a portion of a string and return the extracted portion in a new string. The syntax is as follows:
string.slice(start,end)
Copy the code
This method takes two parameters:
- Start: Mandatory. The starting subscript of the segment to be cut, with the first character position 0. If it is negative, it is truncated from the tail.
- End: Optional. The subscript at the end of the clip to be captured. 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 argument is negative, it specifies the position from the end of the string.
If start is negative, this parameter specifies the position from the end of the string. That is, -1 is the last character of the string, -2 is the second-to-last character, and so on:
let str = "abcdef";
str.slice(1.6); // output result: "bcdef"
str.slice(1); // Output result: "bcdefg"
str.slice(); // Output result: "abcdefg"
str.slice(-2); // Output result: "fg"
str.slice(6.1); // Output result: ""
Copy the code
Note that the substring returned by this method includes the character at the beginning but not the character at the end.
(2) the substr ()
The substr() method is used to extract a specified number of characters from the beginning subscript in a string. The syntax is as follows:
string.substr(start,length)
Copy the code
This method takes two parameters:
- Start a necessity. The starting index of the substring to extract. It has to be a number. If it is negative, the argument declares the position from the end of the string. That is, -1 is the last character in the string, -2 is the second-to-last character, and so on.
- Length: Optional. Number of characters in a substring. It has to be a number. If this parameter is omitted, the string from the beginning of stringObject to the end is returned.
let str = "abcdef";
str.substr(1.6); // Output result: "bcdefg"
str.substr(1); // "bcdefg" is equivalent to intercepting [1,str.length-1]
str.substr(); // "abcdefg" is equivalent to intercepting [0,str.length-1]
str.substr(-1); // Output result: "g"
Copy the code
(3) the substring ()
The substring() method is used to extract the character of a string intermediate between two specified subscripts. The syntax is as follows:
string.substring(from, to)
Copy the code
This method takes two parameters:
- From: necessary. A non-negative integer specifying the position in the string of the first character of the substring to be extracted.
- To: Optional. A non-negative integer one more than the position in the string of the last character of the substring to be extracted. If omitted, the substring is returned up to the end of the string.
Note: If the arguments from and to are equal, this method returns an empty string (that is, a string of length 0). If from is larger than to, the method swaps these two arguments before extracting the substring. And the method does not accept negative arguments; if the argument is negative, the string is returned.
let str = "abcdef";
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); // output "bcdef" [1,6]
str.substring(-1); // Output result: "abcdefg"
Copy the code
Note that the substring returned by this method includes the character at the beginning but not the character at the end.
7. String case conversion
The toLowerCase() and toUpperCase() methods can be used to convert the case of a string.
(1) toLowerCase ()
ToLowerCase () : this method is used to convert a string toLowerCase.
let str = "adABDndj";
str.toLowerCase(); // Output result: "adabdndj"
Copy the code
(2) the toUpperCase ()
ToUpperCase () : this method is used to convert a string toUpperCase.
let str = "adABDndj";
str.toUpperCase(); // Output result: "ADABDNDJ"
Copy the code
We can use this method to uppercase the first character in a string:
let word = 'apple'
word = word[0].toUpperCase() + word.substr(1)
console.log(word) // Output result: "Apple"
Copy the code
8. String pattern matching
The replace(), match(), and search() methods can be used to match or replace characters.
(1) the replace ()
Replace () : This method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression. The syntax is as follows:
string.replace(searchvalue, newvalue)
Copy the code
This method takes two parameters:
- Searchvalue: Required. RegExp object that specifies the substring or schema to replace. If the value is a string, it is treated as a direct quantitative text pattern to retrieve, rather than being converted to a RegExp object first.
- Newvalue: required. A string value. Specifies a function that replaces text or generates replacement text.
let str = "abcdef";
str.replace("c"."z") // Output result: abzdef
Copy the code
Perform a global substitution, 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'
Copy the code
Note: If regexp has the global flag G, the replace() method replaces all matching substrings. Otherwise, it replaces only the first matching substring.
(2) the match ()
Match () : This method is used to retrieve a specified value within a string, or to 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. The syntax is as follows:
string.match(regexp)
Copy the code
The method argument regexp is required, specifying the regEXP object of the pattern to match. 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 of matching results. The contents of the 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]
Copy the code
(3) the search ()
The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. The syntax is as follows:
string.search(searchvalue)
Copy the code
The parameter regex to this method can be either a substring to retrieve in a string, or a RegExp object to retrieve.
Note: To perform a case-insensitive retrieval, append the flag I. This method does not perform a global match; it ignores the flag G, which returns only 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/) // Output: 1
Copy the code
9. Remove end-of-string whitespace
Trim (), trimStart(), and trimEnd() can be used to remove whitespace at the beginning and end of a string. Whitespace includes Spaces, tabs, newlines, and other whitespace.
(1) the trim ()
The trim() method removes whitespace at the beginning and end of a string without changing the original string:
let str = " abcdef "
str.trim() // Output result: "abcdef"
Copy the code
Note that this method does not apply to null, undefined, or Number types.
(2) trimStart ()
The trimStart() method behaves like trim(), but returns a new string with whitespace removed from the beginning of the original string, without modifying the original string:
const s = ' abc ';
s.trimStart() // "abc "
Copy the code
(3) trimStart ()
The trimEnd() method behaves like trim(), but returns a new string with whitespace removed from the end of the original string, without modifying the original string:
const s = ' abc ';
s.trimEnd() // " abc"
Copy the code
10. Get the string itself
The valueOf() and toString() methods both return the valueOf the string itself and feel useless.
(1) the valueOf ()
ValueOf () : returns the original valueOf a string object, which is usually called automatically by JavaScript rather than explicitly in code.
let str = "abcdef"
console.log(str.valueOf()) // "abcdef"
Copy the code
(2) the toString ()
ToString () : Returns the string object itself
let str = "abcdef"
console.log(str.toString()) // "abcdef"
Copy the code
11. Repeat a string
The repeat() method returns a new string, repeating the original string n times:
'x'.repeat(3) // Output result: "XXX"
'hello'.repeat(2) // Output: "hellohello"
'na'.repeat(0) // Output result: ""
Copy the code
If the argument is a decimal, round down:
'na'.repeat(2.9) // Output result: "nana"
Copy the code
Error if argument is negative or Infinity:
'na'.repeat(Infinity) // RangeError
'na'.repeat(-1) // RangeError
Copy the code
If the argument is a decimal between 0 and -1, it is equal to 0, because the round is performed first. If the decimal number between 0 and -1 is rounded to -0, repeat is regarded as 0.
'na'.repeat(-0.9) // Output result: ""
Copy the code
If the argument is NaN, this equals 0:
'na'.repeat(NaN) // Output result: ""
Copy the code
If the argument of the repeat is a string, it is converted to a number first.
'na'.repeat('na') // Output result: ""
'na'.repeat('3') // Output result: "nanana"
Copy the code
12. Complete the string length
The padStart() and padEnd() methods complement the length of the string. If a string is not of a specified length, the header or tail is completed.
(1) padStart ()
PadStart () is used for head completion. The method takes two arguments, the first of which is a number representing the length of the string after completion. The second argument is the string used for completion.
If the length of the original string is equal to or greater than the specified minimum length, the original string is returned:
'x'.padStart(1.'ab') // 'x'
Copy the code
If the sum of the length of the completion string and the original string exceeds the specified minimum length, the completion string exceeding the number of bits is truncated:
'x'.padStart(5.'ab') // 'ababx'
'x'.padStart(4.'ab') // 'abax'
Copy the code
If the second argument is omitted, the default space is used to complete the length:
'x'.padStart(4.'ab') // 'a '
Copy the code
A common use of padStart() is to specify the number of digits for numeric completion. A recent requirement of the author was to complete the number of pages returned by three digits, such as 001 on page 1, using this method:
"1".padStart(3.'0') // Output result: '001'
"15".padStart(3.'0') // Output result: '015'
Copy the code
(2) padEnd ()
PadEnd () is used for tail completion. This method also takes two parameters, the first parameter is the maximum length that string completion takes effect, and the second parameter is the string used for completion:
'x'.padEnd(5.'ab') // 'xabab'
'x'.padEnd(4.'ab') // 'xaba'
Copy the code
13. Convert the string to a number
The parseInt() and parseFloat() methods are both used to convert strings to numbers.
(1) the parseInt ()
The parseInt() method is used to parse a string and return an integer. The syntax is as follows:
parseInt(string, radix)
Copy the code
This method takes two parameters:
- String: required. String to be parsed.
- Radix: Optional. Represents the radix of the number to be parsed. The value is between 2 and 36.
​
When the radix parameter is 0 or not set, parseInt() determines the cardinality of the number based on string.
parseInt("10"); // Output: 10
parseInt("17".8); // Output result: 15 (8+7)
parseInt("010"); // Output result: 10 or 8
Copy the code
When the parameter radix value starts with “0x” or “0x”, it will be based on 16:
parseInt("0x10") // Output: 16
Copy the code
If this parameter is less than 2 or greater than 36, parseInt() returns NaN:
parseInt("50".1) // Output result: NaN
parseInt("50".40) // Output result: NaN
Copy the code
Only the first digit in the string is returned, until the first non-digit character is encountered:
parseInt("40 4years") // Output: 40
Copy the code
If the first character of the string cannot be converted to a number, NaN is returned:
parseInt("new100") // Output result: NaN
Copy the code
Spaces at the beginning and end of strings are allowed:
parseInt("60") // Output: 60
Copy the code
(2) the parseFloat ()
The parseFloat() method parses a string and returns a floating point number. This method specifies whether the first character in a string is a number. If so, the string is parsed until the end of the number is reached, and then the number is returned as a number, not as a string. The syntax is as follows:
parseFloat(string)
Copy the code
ParseFloat parses its string arguments into floating point numbers and returns them. If a character other than a plus or minus sign (+ or -), digit (0-9), decimal point, or exponent (e or e) in scientific notation is encountered during parsing, it ignores that character and all subsequent characters and returns the currently parsed float. Whitespace at the beginning of the argument string is ignored.
parseFloat("10.00") // Output: 10.00
parseFloat("10.01") // The output is 10.01
parseFloat("10.01") // The output is -10.01
parseFloat("40.5 years") // Output: 40.5
Copy the code
If the first character of the argument string cannot be parsed into a number, parseFloat returns NaN.
parseFloat("new40.5") // Output result: NaN
Copy the code
Today is over here, if you feel useful click like, favorites, follow me!
Recommended reading:
- Programmer interview essential soft skills, worth collecting!
- Gold nine silver ten, are you ready for the interview? (With 30W word front end test summary)
- What details about JavaScript data types do you not know?
- Do you know all 24 JavaScript looping methods?
- A brief discussion on JavaScript variable promotion
- Yahoo’s 35 catch-22 rules, how many do you know?