In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you what JavaScript commonly used string methods are, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Preface
What are the commonly used string methods in JavaScript
1. Get string length the string in JavaScript has a length attribute, which can be used to get the length of the string: const str = 'hello';str.length / / output result: 52. Gets the value of the specified position of the string
Both the charAt () and charCodeAt () methods can get the value of the specified location through the index:
The charAt () method gets the character at the specified position
The charCodeAt () method gets the Unicode value specified as a worthy character.
(1) charAt ()
The charAt () method returns the characters at the specified position. The syntax is as follows:
String.charAt (index)
Index represents the index value of the character in the string:
Const str = 'hello';str.charAt (1) / / output result: e
We know that a string can also get the corresponding character directly through the index value, so what's the difference between it and charAt ()? Let's look at 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
You can see that when the value of index is not within the length of str, str [index] returns undefined, while charAt (index) returns an empty string; in addition, str [index] is not compatible with ie6-ie8,charAt (index).
(2) charCodeAt ()
CharCodeAt (): this method returns the Unicode value of the character at the specified index position. The return value is an integer between 0 and 65535, indicating the UTF-16 code unit at the given index. If there are no characters at the specified position, NaN is returned:
Let str = "abcdefg"; console.log (str.charCodeAt (1)); / / "b"-> 98
With this method, you can get the characters in the string that specify a range of Unicode coding values. For example, the Unicode encoding range of the number 0x9 is 48057, which can be used to filter the numbers in a string, although it will be more convenient if you are more familiar with regular expressions.
3. Retrieve whether the string contains a specific sequence
All five methods can be used to retrieve whether a string contains a specific sequence. The index value of the specified element obtained by the first two methods, and only returns the position of the value that was matched for the first time. The last three methods return a Boolean value indicating whether it matches the specified value.
Note: all five methods are case sensitive!
(1) indexOf ()
IndexOf (): looks for a character, returns the position to which it first matched, otherwise returns-1. Its syntax is as follows:
String.indexOf (searchvalue,fromindex)
This method has two parameters:
Searchvalue: required, specifying the string value to be retrieved
Fromindex: an optional integer parameter that specifies where to start the retrieval in the string. Its legal value is 0 to string.length-1. If this is omitted, the retrieval starts with the first character of the string.
Let str = "abcdefgabc"; console.log (str.indexOf ("a")); / / output result: 0console.log (str.indexOf ("z")); / / output result:-1console.log (str.indexOf ("c", 4)) / / output result: 9 (2) lastIndexOf ()
LastIndexOf (): find a character, return the last matching position, otherwise return-1
Let str = "abcabc"; console.log (str.lastIndexOf ("a")); / / output result: 3console.log (str.lastIndexOf ("z")); / / output result:-1
This method is similar to indexOf (), except that the search order is different. IndexOf () is a positive search 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 of this method is as follows:
String.includes (searchvalue, start)
This method has two parameters:
Searchvalue: required, string to find
Start: optional. Set to start searching from that location. Default is 0.
Let str = 'Hello Worldwide worlds: Str.output (' o') / / output result: truestr.includes ('z') / / output result: falsestr.includes ('eBay, 2) / / output result: false (4) startsWith ()
StartsWith (): this method is used to detect whether a string begins with a specified substring. Returns true if it begins with the specified substring, otherwise false. The syntax is the same as the includes () method above.
Let str = 'Hello world leaders: str.startsWith (' Hello') / / output result: truestr.startsWith ('Helle') / / output result: falsestr.startsWith (' wo', 6) / / output result: true (5) endsWith ()
EndsWith (): this method is used to determine whether the current string ends with a specified substring. Returns true if the passed substring is at the end of the search string, otherwise it returns false. The syntax is as follows:
String.endsWith (searchvalue, length)
This method has two parameters:
Searchvalue: required, substring to search
Length: sets the length of the string. The default value is the original string length string.length.
Let str = 'Hello world leaders: str.endsWith ('!') / / output result: truestr.endsWith ('llo') / / output result: falsestr.endsWith (' llo', 5) / / output result: true
As you can see, when the second parameter is set to 5, it is retrieved from the first five characters of the string, so true is returned.
4. Concatenate multiple strings
The concat () method is used to concatenate two or more strings. This method does not change the original string and returns a new string that concatenates two or more strings. The syntax is as follows:
String.concat (string1, string2,..., stringX)
The parameters string1, string2,..., and stringX are required, and they will be concatenated as one or more string objects of a string.
Let str = "abc"; console.log (str.concat ("efg")); / / output result: "abcefg" console.log (str.concat ("efg", "hijk")); / / output result: "abcefghijk"
Although the concat () method is specifically used to concatenate strings, the addition operator + is most commonly used in development because it is simpler.
5. Split a string into an array
The split () method is used to split a string into an array of strings. This method does not change the original string. The syntax is as follows:
String.split (separator,limit)
This method has two parameters:
Separator: required. A string or regular expression that splits the string from the place specified by the 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 is split, regardless of its length.
Let str = "abcdef"; str.split ("c"); / / output result: ["ab", "def"] str.split ("", 4) / / output result: ['averse,' baked, 'cased,' d']
If an empty string is used as a separator, each character in the string is split.
Str.split (""); / / output result: ["a", "b", "c", "d", "e", "f"]
In fact, when dividing a string into an array, you can split multiple splitters at the same time, using regular expressions:
Const list = "apples,bananas;cherries" const fruits = list.split (/ [,;] /) console.log (fruits); / / output result: ["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 portion of a string and return the extracted part as a new string. The syntax is as follows:
String.slice (start,end)
This method has two parameters:
Start: yes. The starting subscript of the fragment to be intercepted, with the first character position 0. If it is negative, it is intercepted from the tail.
End: optional. The subscript at the end of the clip 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 the parameter is negative, it specifies the position from the end of the string.
As mentioned above, if start is negative, this parameter specifies the position starting at the end of the string. That is,-1 refers to the last character of the string,-2 refers to the penultimate character, and so on:
Let str = "abcdef"; str.slice (1Power6); / / 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: "
Note that the substring returned by this method includes the character at the beginning, but not the character at the end.
(2) substr ()
The substr () method is used to extract a specified number of characters from a string starting with the starting subscript. The syntax is as follows:
String.substr (start,length)
This method has two parameters:
Start is required. The starting subscript of the substring to be extracted. Must be a numeric value. If it is a negative number, 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 penultimate 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 the stringObject is returned.
Let str = "abcdef"; str.substr (1Power6); / / output result: "bcdefg" str.substr (1); / / output result: "bcdefg" is equivalent to intercepting [1memstr.roomthmur1] str.substr (); / / output result: "abcdefg" is equivalent to intercepting [0herostr.bearthmur1] str.substr (- 1); / / output result: "g" (3) substring ()
The substring () method is used to extract characters that are mediated between two specified subscripts. The syntax is as follows:
String.substring (from, to)
This method has two parameters:
From: required. A non-negative integer that specifies the position of the first character of the substring to be extracted in the string.
To: optional. A non-negative integer that is 1 more positioned in string than the last character of the substring to be extracted. If this parameter is omitted, the substring returned will go all the way to the end of the string.
Note: if the parameters from and to are equal, the method returns an empty string (that is, a string of length 0). If from is larger than to, the method swaps these two parameters before extracting the substring. And the method does not accept a negative parameter, and if the parameter is a negative number, the string is returned.
Let str = "abcdef"; str.substring (1Magne6); / / output result: "bcdef" [1Magne6) str.substring (1); / / output result: "bcdefg" [1Magne6) str.substring (1) str.substring (); / / output result: "abcdefg" [0quotient str.futhmur1] str.substring (6Magne1); / / output result "bcdef" [1Magne6) str.substring (- 1); / / output result: "abcdefg"
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 for case conversion of strings.
(1) toLowerCase () toLowerCase (): this method is used to convert strings to lowercase. Let str = "adABDndj"; str.toLowerCase (); / / output result: "adabdndj" (2) toUpperCase ()
ToUpperCase (): this method is used to convert strings to uppercase.
Let str = "adABDndj"; str.toUpperCase (); / / output result: "ADABDNDJ"
We can use this method to capitalize the first letter in the string:
Let word = 'apple'word = word [0] .toUpperCase () + word.substr (1) console.log (word) / / output result: "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 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)
This method has two parameters:
Searchvalue: required. A RegExp object that specifies the substring or the schema to replace. If the value is a string, it is treated as the direct text pattern to retrieve, rather than being first converted to a RegExp object.
Newvalue: required. A string value. Specifies the function that replaces the text or generates the alternate text.
Let str = "abcdef"; str.replace ("c", "z") / / output result: abzdef
Perform a global replacement, ignoring case:
Let str= "Mr Blue has a blue house and a blue car"; str.replace (/ blue/gi, "red"); / / output result:'Mr red has a red house and a red car'
Note: if regexp has the global flag g, then the replace () method replaces all matching substrings. Otherwise, it replaces only the first matching substring.
(2) match ()
Match (): this method is used to retrieve a specified value within a string or to find a match of one or more regular expressions. This method is similar to indexOf () and lastIndexOf (), but it returns the specified value instead of the position of the string. The syntax is as follows:
String.match (regexp)
The parameter regexp of this method 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 the regexp has the global flag g.
Let str = "abcdef"; console.log (str.match ("c")) / / ["c", index: 2, input: "abcdef", groups: undefined] (3) search ()
The search () method is used to retrieve a substring specified in a string or to retrieve a substring that matches a regular expression. The syntax is as follows:
String.search (searchvalue)
The parameter regex of this method can be either a substring to be retrieved in string or a RegExp object to be retrieved.
Note: to perform a case-ignored retrieval, append the flag I. This method does not perform a global match, it ignores the flag g, that is, it only returns 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/) / / output result: 19. Remove the trailing space character of a string
The trim (), trimStart (), and trimEnd () methods can be used to remove leading and trailing white space characters from the beginning and end of a string, including: spaces, tabs tab, newline characters, and so on.
(1) trim ()
The trim () method is used to remove the white space at the beginning and end of a string, which does not change the original string:
Let str = "abcdef" str.trim () / / output result: "abcdef"
Note that this method does not apply to null, undefined, Number types.
(2) trimStart ()
The trimStart () method behaves the same as trim (), but returns a new string with white space removed from the beginning of the original string without modifying the original string:
Const s = 'abc'; s.trimStart () / / "abc" (3) trimEnd ()
The trimEnd () method behaves the same as trim (), but returns a new string with white space removed from the end of the original string without modifying the original string:
Const s = 'abc'; s.trimEnd () / / "abc" 10. Get the string itself
Both the valueOf () and toString () methods return the value of the string itself, which does not feel useful.
(1) valueOf ()
ValueOf (): returns the original value of a string object, which is usually called automatically by JavaScript, rather than explicitly in the code.
Let str = "abcdef" console.log (str.valueOf ()) / / "abcdef" (2) toString ()
ToString (): returns the string object itself
Let str = "abcdef" console.log (str.toString ()) / / "abcdef" 11. Repeat a string
The repeat () method returns a new string, which means that the original string is repeated n times:
'x'.repeat (3) / / output result: "xxx"' hello'.repeat (2) / / output result: "hellohello" 'na'.repeat (0) / / output result: "
If the parameter is a decimal, it is rounded down:
'na'.repeat (2.9) / / output result: "nana"
If the parameter is negative or Infinity, an error will be reported:
'na'.repeat (Infinity) / / RangeError'na'.repeat (- 1) / / RangeError
If the parameter is a decimal between 0 and-1, it is equivalent to 0 because the rounding operation is performed first. The decimal from 0 to-1, rounded to-0, is regarded as 0 for repeating.
'na'.repeat (- 0.9) / / output result: "
If the parameter is NaN, it is equivalent to 0:
'na'.repeat (NaN) / / output result: "
If the argument to repeat is a string, it is converted to a number first.
'na'.repeat (' na') / / output result: "'na'.repeat (' 3') / / output result:" nanana "12. Complete the length of the string
The padStart () and padEnd () methods are used to complete the length of a string. If a string is not long enough, it will be completed at the head or tail.
(1) padStart ()
PadStart () is used for head completion. The method has two parameters, the first of which is a number that represents the length of the string after completion, and the second parameter is the string used to complete.
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'
If the sum of the length of the string used to complete and the original string exceeds the specified minimum length, the completion string that exceeds the number of digits is truncated:
'x'.padStart (5, 'ab') / /' ababx''x'.padStart (4, 'ab') / /' abax'
If the second parameter is omitted, the space completion length is used by default:
'x'.padStart (4, 'ab') / /' a'
The common use of padStart () is to specify the number of digits for numerical completion. One of the requirements recently made by the author is to complete the number of returned pages to three digits. For example, page 1 is displayed as 001, and you can use this method to operate:
"1" .padStart (3,'0') / / output result: '001' "15" .padStart (3,' 0') / / output result: '015' (2) padEnd ()
PadEnd () is used for tail completion. This method also receives two parameters, the first parameter is the maximum length at which the string completion takes effect, and the second parameter is the string used to complete:
'x'.padEnd (5, 'ab') / /' xabab''x'.padEnd (4, 'ab') / /' xaba'13. String converted to a number
Both the parseInt () and parseFloat () methods are used to convert a string to a number.
(1) parseInt ()
The parseInt () method is used to parse a string and return an integer. The syntax is as follows:
ParseInt (string, radix)
This method has two parameters:
String: required. The string to be parsed.
Radix: optional. Represents the cardinality of the number to parse. The value is between 2 and 36.
When the value of the parameter radix is 0, or when it is not set, parseInt () determines the cardinality of the number based on string.
ParseInt ("10"); / / output result: 10parseInt ("17", 8); / / output result: 15 (8 / 7) parseInt ("010"); / / output result: 10 or 8
When the value of the parameter radix begins with "0x" or "0X", it will be based on 16:
ParseInt ("0x10") / / output result: 16
If the parameter is less than 2 or greater than 36, parseInt () returns NaN:
ParseInt ("50", 1) / / output result: NaNparseInt ("50", 40) / / output result: NaN
Only the first number in the string is returned when the first character that is not a number is encountered:
ParseInt ("40 4years") / / output result: 40
If the first character of the string cannot be converted to a number, NaN is returned:
ParseInt ("new100") / / output result: NaN
Spaces at the beginning and end of a string are allowed:
ParseInt ("60") / / output: 60 (2) parseFloat ()
The parseFloat () method parses a string and returns a floating point number. This method specifies whether the first character in the 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)
ParseFloat parses its string parameters into floating-point numbers and returns them. If a character other than a positive or negative sign (+ or -), a number (0-9), a decimal point, or an index (e or E) in scientific notation is encountered during parsing, it ignores that character and all subsequent characters and returns the floating-point number that has currently been parsed. At the same time, the white space character in the first bit of the parameter string is ignored.
ParseFloat ("10.00") / / output result: 10.00parseFloat ("10.01") / / output result: 10.01parseFloat ("- 10.01") / / output result:-10.01parseFloat ("40.5 years") / / output result: 40.5
ParseFloat returns NaN if the first character of the parameter string cannot be parsed into a number.
ParseFloat ("new40.5") / / output result: NaN above is all the content of this article "what are the common string methods in JavaScript?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.