Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the string of Javascript

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to use Javascript strings". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Javascript strings.

Catalogue

String length: length

Gets the value of the specified position of the string

CharAt ()

CharCodeAt ()

String check to see if it contains a value

IndexOf ()

LastIndexOf ()

Includes ()

StartsWith ()

EndsWith ()

String concatenation

Concat

'+' sign

Split a string into an array

Split ()

Intercept string

Slice ()

Substr ()

Substring ()

String case conversion

ToLowerCase ()

ToUpperCase ()

String pattern matching

Replace ()

ReplaceAll ()

Match ()

Search ()

Remove string white space character

Trim ()

TrimStart ()

TrimEnd ()

Other types are converted to strings

ToString ()

String ()

Implicit conversion

JSON.stringify ()

Repeat a string

Repeat ()

Complete the length of the string

PadStart ()

PadEnd ()

ParseFloat ()

JSON.parse ()

Number ()

Summary

String length: length gets the value of the specified position of the string charAt ()

Return value

Str.charAt (2) / / cstr [2] / / cstr.charAt (30) / / 'str [30] / / undefinde

When the value of index is not within the length of str, str [index] returns undefined, while charAt (index) returns an empty string.

Note: strindex is not compatible. Ie6-ie8,charAt (index) is compatible.

CharCodeAt ()

Gets the Unicode value of the string index position character

Str.charAt (2) / / cstr [2] / / cstr.charAt (30) / / 'str [30] / / undefinde string checks whether it contains a value indexOf ()

Find a character, return the index position that was matched for the first time, otherwise return-1, search in positive order:

Str.indexOf ('e') / / 4 Index location str.indexOf ('e') / /-1

Syntax: string.indexOf (value,startIndex)

Value: required, specifying the string value to be retrieved

StartIndex: optional integer parameter, default 0, positive order search starts the location of the search. Its legal value is 0 to string.length-1.

LastIndexOf ()

Find a character, return the last matching position, otherwise return-1, contrary to indexOf, look up backwards:

Str.lastIndexOf ('e') / / 10str.lastIndexOf ('eScript8) / / flashback search for eUnix / 4str.lastIndexOf within index 0-8 / / flashback search for eUnip /-1 within index 0-3

Syntax: string.lastIndexOf (value,startIndex)

Value: required, specifying the string value to be retrieved

StartIndex: optional integer parameter, default string.length-1, flashback lookup start index position. Its legal value is 0 to string.length-1.

Includes ()

Determines whether the string contains the specified substring. Returns true if a matching string is found, false otherwise.

Str.includes ('e') / / truestr.includes ('eBay Magazine 11) / / false

Syntax: string.includes (value, startIndex)

Value: required, specifying the string value to be retrieved

StartIndex: optional integer parameter, default 0, find the starting index position. Its legal value is 0 to string.length-1.

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.

Str.startsWith ('ab') / / truestr.startsWith (' ef') / / falsestr.startsWith ('ef',4) / / true

Syntax: string.startsWith (value, startIndex)

Value: required, specifying the string value to be retrieved

StartIndex: optional integer parameter, default 0, find the starting index position. Its legal value is 0 to string.length-1.

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.

Str.endsWith ('ba') / / truestr.endsWith (' ef') / / falsestr.endsWith ('ef',6) / / true

Syntax: string.endsWith (value, length)

Value: required, specifying the string value to be retrieved

Length: the length of the substring. Default is the original string length string.length.

String concatenation concat

Concatenate two or more strings. This method does not change the original string and returns a new string that concatenates two or more strings.

Let a = 'asdf'let b =' 123'let s = a.concat (b) let S2 = a + bconsole ('asdf'' 123' 'asdf123'' asdf123')

Syntax: string.concat (string1, string2,..., stringX)

Concatenate string1, string2 after the string string. StringX

'+' sign

As shown in the contact example above, this method is generally used, which is simple and efficient.

The string is split into an array split ()

Divide a string into an array of strings. This method does not change the original string.

Str.split ('') / ["a", "b", "c", "d", "e", "f", "g", "h", "g", "f", "e", "d", "c", "b", "a"] str.split (', 4) / / ["a", "b", "c", "d"] str.split ('') 20) / ["a", "b", "c", "d", "e", "f", "g", "h", "g", "f", "e", "d", "c", "b", "a"]

Syntax: string.split (separator,limit)

Separator: required. A string or regular expression that splits the string from the place specified by this 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.

Intercept the string slice ()

Extract a portion of the string and return the extracted part as a new string.

Str.slice (1mam 3) / / bcstr.slice (- 3mae Murray 1) / / cb

Syntax: string.slice (start,end)

Start: yes. The starting index 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.

If start is negative, then end should be greater than start and less than 0

The substring returned by this method includes the character at start but not the character at end

Substr ()

Used to extract a specified number of characters from a string starting with the starting subscript.

Str.substr (5) / / fghgfedcbastr.substr (5pm 3) / / fgh

Syntax: string.substr (start,length)

Start: required. The starting subscript of the substring to be extracted. Must be a numeric value. If it is a negative number, the parameter declares the position from the end of the string, which can be a negative number, indicating that it starts at the end.

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 string is returned.

Substring ()

Used to extract characters mediated by a string between two specified subscripts

Str.substring (3) / / destr.substring (5) / / de

Syntax: string.substring (start, end)

Start: required. A non-negative integer that specifies the position of the first character of the substring to be extracted in the string.

End: 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:

Both start and end do not accept substrings returned by negative numbers that contain start but not end. If start=end is returned, empty strings are returned. If start < end, the method will automatically swap these two parameter strings for case conversion toLowerCase ()

Converts the string to lowercase.

Let t = 'AXC't.toLowerCase () / / axctoUpperCase ()

Converts a string to uppercase.

Str.toUpperCase () / / ABCDEFGHGFEDCBA string pattern matching replace ()

Used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression.

Str.replace ('bake Magne11) / / a11cdefghgfedcbastr.replace (/ bdebase gMagne11) / / a11cdefghgfedc11a g: indicates the global. If not, the first one is replaced by default. I: ignores case.

Syntax: string.replace (oldValue, newValue)

OldValue: 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.

ReplaceAll ()

Global replacement of the replace () method:

Str.replace (/ bstroke gMagn11) is equivalent to str.replaceAll ('baccalaure11)

Match ()

Used to retrieve the 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.

Str.match ('ghg') / / ["ghg", index: 6, input: "abcdefghgfedcba", groups: undefined] str.match (/ ghg/g) / / ["ghg"] str.match (/ a ghg g) / / ["a", "a"] str.match (/ tUnig) / / null

Syntax: string.match (regexp)

Regexp is required, specifying the RegExp object of the pattern to match.

This method returns an array that holds the matching results. The contents of the array depend on whether the regexp has the global flag g.

Search ()

Used to retrieve a substring specified in a string, or to retrieve a substring that matches a regular expression.

Str.search (/ ghg/) / / 6str.search (/ a /) / / 0str.search (/ a _ Unig) / / 0str.search (/ t _ g) /-1

Syntax: string.search (value)

Regex can be a substring that needs to be retrieved in string, or a RegExp object that needs 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. Returns the starting position of the first substring in the str that matches the regexp. Remove the string white space character trim ()

Used to remove the white space character at the beginning and end of a string, which does not change the original string. This method is not suitable for null, undefined and Number types.

Let s = '123' s.trim () / /' 123'trimStart ()

Used to remove the white space at the beginning of a string, which does not change the original string.

Let s = '123' s.trimStart () / /' 123' trimEnd ()

Used to remove the white space at the end of a string, which does not change the original string.

Let s = '123' s.trimEnd () / /' 123' other types are converted to string toString ()

For: Boolean,Array,Number

Let arr = [1Jing 2jue 3] let num = 123let bool = truelet obj = {AGV 1} arr.toString () / / '1Med 2Med 3mu num.toString () / /' 123'bool.toString () / / 'true'obj.toString () / /' [object Object]'

Syntax: notStr.toString ()

String ()

For: Boolean,Array,Number

Let arr = [1Jing 2jue 3] let num = 123let bool = truelet obj = {AGV 1} String (arr) / / '1Med 2Med 3mage string (num) / /' 123'String (bool) / / 'true'String (obj) / /' [object Object]'

Syntax: String (notStr)

Implicit conversion

Non-string + string = string, implicitly convert the original data type to a string, and then add a new string.

For: Boolean,Array,Number,null

Let arr = [1meme 2meme 3] let num = 123let bool = truelet obj = {aVera 1} arr+'' / / '1Magi 2Meiji 3pia arrymaglypt' / / '1je 2pas / /' 123tmlmu boollies / 'true'obj+'' / /' [object Object] 'null+'' / /' null'JSON.stringify ()

For: Boolean,Array,Number,null,undefined

Let arr = [1Magazine 2 bool 3] let num = 123let bool = truelet obj = {avision 1} JSON.stringify (arr) / / '123'JSON.stringify (bool) / /' true'JSON.stringify (obj) / /'{"a": 1} 'JSON.stringify (null) /' null'JSON.stringify (NaN) / 'null'

Restore uses JSON.parse ()

Let arr = let num = 123let bool = truelet obj = {truelet obj 1} JSON.parse (JSON.stringify (arr)) / / [1Yue2Yue3] JSON.parse (JSON.stringify (num)) / / 123JSON.parse (JSON.stringify (bool)) / / trueJSON.parse (JSON.stringify (obj)) / {a123let bool 1} JSON.parse (JSON.stringify (null)) / / nullJSON.parse (JSON.stringify (NaN) / / null repeats a string repeat ()

Returns a new string, indicating that the original string will be repeated n times

'cv'.repeat (3) / /' cvcvcv''cv'.repeat (0) / /''cv'.repeat (2. 6) / /' cvcv''cv'.repeat ('3') / / 'cvcvcv''cv'.repeat (' 3a') / /'

Syntax: string.repeat (number)

Number: number of repeats

Note:

If 0, the empty substring will be rounded down negative or Infinity will report a negative decimal or NaN between 0 and-1, which is equal to 0. If number is a string, it will first be converted to a numeric type string and will automatically be converted to the corresponding numeric type, and then repeat a non-numeric type string, which is equivalent to 0 to complete the string length padStart ().

Head completion

Let t = 'mosowe't.padStart (1) / /' mosowe't.padStart (10) / / 'nbnbmosowe't.padStart (10) / /' mosowe't.padStart (10) / / 'mosowe'

Syntax: string.padStart (length,str)

Length: the length of the string after completion

Str: the string used to complete

Note:

If the length of the original string is equal to or greater than the specified minimum length, the original string is returned. If the sum of the length of the string used to complete and the original string exceeds the specified minimum length, the string that exceeds the specified minimum length will be truncated. If the second parameter is omitted, the space completion length will be used by default. If the second parameter is empty, padEnd () will not be completed.

For the completion at the end, see padStart ()

The string is converted to a number parseInt ()

ParseInt ("10") / / 10parseInt ("10.11") / / 10parseInt ("16", 8) / / 14 = 8x6, converted to octal parseInt ("010") / / 10, it is said that some browsers are 8, but I have tried several domestic browsers, all of which are 10Jie parseInt ("") / / NaNparseInt ("unh") / / NaNparseInt ("123tt") / 123parseInt ("tt123") / / NaN.

Syntax: parseInt (string, radix)

String: required. The string to be parsed

Radix: optional. Represents the cardinality of the number to parse. The value is between 2 and 36, with a default of 10.

ParseFloat ()

Convert to decimal floating point number

ParseFloat ("10") / / 10parseFloat ("10.11") / / 10.11parseFloat ("10.11.11111") / / 10.11parseFloat ("010") / / 10parseFloat ("") / / NaNparseFloat ("unh") / / NaNparseFloat ("123tt") / / 123parseFloat ("tt123") / / NaN

Syntax: parseFloat (string)

JSON.parse () JSON.parse ("10") / / 10JSON.parse ("10.11") / / 10.11JSON.parse ("10.11.11111") / / errorJSON.parse ("010") / / errorJSON.parse ("") / / errorJSON.parse ("unh") / / errorJSON.parse ("123tt") / / errorJSON.parse ("tt123") / / error

Syntax: JSON.parse (string)

Number () Number ('') / / 0Number ('10') / / 10Number (' 010') / / 10Number ('2.3') / / 2.3Number (' 2.3.3') / / NaNNumber ('2TT') / / NaNNumber ('TT2') / / NaN

Syntax: Number (string)

At this point, I believe you have a deeper understanding of "how to use Javascript strings". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report