JavaScript String Object

Source: Internet
Author: User
Tags instance method

Original: JavaScript String Object

String Object 1. Introduced

String object that operates on a string, such as intercepting a substring, finding a string/character, converting a case, and so on.

2. Definition Method 2.1 new string (value) constructor: Returns a String object with content Value

Parameters:

①value {string}: String

return value:

{String Object} returns a String object with content value

Example:

var demostr = new String (' abc '); Console.log (typeof Demostr); = Objectconsole.log (DEMOSTR); = ABC

2.2 Direct Assignment (recommended)

Example:

var demostr = ' abc '; Console.log (typeof Demostr); Stringconsole.log (DEMOSTR); = ABC

3. Instance Property 3.1 Length: Returns the number of characters in a string
var s = ' abc '; Console.log (s.length); = = 3console.log (' Happy New Year '. length); + 4: A Chinese character is also calculated as 1 quantity console.log (". Length"); = 0: empty string returns 0

4. Example Methods

Note: The instance method of the string does not change the string itself, only returns the result after the operation.

4.1 charAt (Index): Returns the character at the specified position in a string, starting with the number 0, and returning an empty string if it passes in a value that does not exist

Parameters:

①index {int}: Position index, calculated starting from 0

return value:

{string} returns a character at the specified position in a string, and returns an empty string if it passes in a position value that does not exist

Example:

var s = ' abc '; Console.log (S.charat (1)); = = B: Returns the character of position 1 console.log (s); = = does not affect the original array console.log (S.charat (5)); = = ': Gets a character that does not exist and returns an empty string of length 0

4.2 charCodeAt (Index): Returns the Unicode encoding of the specified position character in a string

Parameters:

①index {int}: Position index, calculated starting from 0

return value:

{Number} returns the Unicode encoding of the specified position character in a string, and returns Nan if a nonexistent position value is passed in

Example:

var s = ' abc '; console.log (s.charcodeat (0)); = 98: Unicode encoding of Character B Console.log (S.charcodeat (5)); = = Nan: Gets a character that does not exist, returns Nan

4.3 concat (Value1,value2 ... valuen): concatenate one or more strings and return the concatenated string

Parameters:

①value1,value2. Valuen {string}: one or more strings

return value:

{string} returns the concatenated string

Example:

var s = ' abc '; Console.log (S.concat (' d ')); = Abcdconsole.log (s); = = ABC: does not affect the original string Console.log (S.concat (' d ', ' e ')); = ABCDE

4.4 IndexOf (value, |startposition): Finds a string or character in the previous instance, and returns the location found (counting from 0). If not found, return-1

Parameters:

①value {string}: String to find

②startposition {int} optional: Starting at the beginning of the lookup, starting from position 0 by default

return value:

{int} returns the location found (counting starting at 0). If not found, return-1

Example:

var s = ' abc '; Console.log (S.indexof (' B ')); = = 1console.log (S.indexof (' d ')); = 1: Console.log not Found (S.indexof (' B ', 2)); +-1: Starting at position 2 (3rd character) find

4.5 lastIndexOf (value, |startposition): Finds a string or character in the instance from the back to the beginning, and returns the location found (counting from 0). If not found, return-1

Parameters:

①value {string}: String to find

②startposition {int} optional: Starting from where to find, default from last

return value:

{int} returns the location found (counting starting at 0). If not found, return-1

Example:

var s = ' abcabc '; Console.log (S.lastindexof (' a ')); + 3: Look forward to Console.log (S.lastindexof (' d ')); = 1: No Return -1console.log (S.lastindexof (' A ', 2) found); + 0: Start looking forward from position 2 (3rd character)

4.6 Localecompare (value): instance compares with parameters, returns comparison results

Parameters:

①value {string}: string to be compared

return value:

0: larger instance than parameter

1: instance is equal to parameter

-1: Smaller instances than parameters

Example:

var s= ' abc '; Console.log (s.localecompare (' ab ')); + 1: the instance is larger than the parameter Console.log (S.localecompare (' abc ')); + 0: Instance and parameter Equal Console.log (S.localecompare (' Abd ')); + = 1: instance is smaller than parameter

  

4.7 Match (REGEXP): Use regular expressions for matching lookups

Parameters:

①regexp {regexp}: Regular expression, eg:/\d+/

return value:

Returns a different result depending on whether the regular expression has an attribute ' G ' or not, and returns {null} if no match is found:

The ① regular expression does not take the property ' G ', performs a match, returns a {single match} result object, and the object contains the following properties:

Array ordinal: Indicates the matching result, 0 matches the text, 1 is from the right 1th parenthesis match result, 2 is the second parenthesis, and so on

Index property: Indicates where the matching text begins at the matching source

Input property: Represents a matching source

② regular expression with the attribute ' G ', performs a global match, finds all matching objects of the string, returns a {string array}: The array element contains each matching object in a string, does not contain a string within the parentheses of the regular expression, and does not provide the index and input properties.

Example:

1. Single match var s = ' a1b2c3d4 '; var mc = S.match (/\d+/); = = Gets the result of the first regular match if (MC! = null) {    console.log (mc.index);//+ = 1: Match the result at the beginning of the matching source    console.log (mc.input)//= > a1b2c3d4: Matching source    console.log (mc[0]);//+ = 1: Get matching Results}//2. Global match var Mcarray = S.match (/\d+/g); = = gets all regular matched numbers if (mcarray! = null) {for    (var i = 0,len=mcarray.length; i < Len; i++) {        var mc=mcarray[i] ;        Console.log (MC); = = 1,2,3,4: Gets the match to the result    }}//3. Parentheses match s = ' a1b2c3d4 '; mc = S.match (/[a-z] ([1-9])/); = = Gets the result of the first regular match if (MC! = null) {    console.log (mc.index);//+ = 0: Match the result at the beginning of the matching source    console.log (mc.input)//= > a1b2c3d4: Match source    Console.log (mc[0]);//+ = A1: Sequence number 0 Indicates the result of the match    Console.log (mc[1]);//= 1 : Ordinal 1 indicates a sub-match result in the first parenthesis}

4.8 Replace (RegExp, REPLACESTR): Replaces a substring that matches a regular expression and returns the replaced string

Parameters:

①regexp {regexp}: Regular expression. eg:/\d+/

②replacestr {string | function}:

1) If the string, which represents the replacement string, is replaced by the string;

The $ character in the string has a special meaning:

$1,$2: A matching subkey representing a left-to-right parenthesis for ① arguments

$&: A subkey that represents the entire ① parameter match

$$: Dollar sign

2) If the function, indicating that each match result calls this function, the function's unique parameter is the matching result, and returns a replacement result.

return value:

{string} returns a substituted string

Example:

var oldstr = ' a1b2c3d4 ';//1. Regular matches to "all" numbers, replaced by: ', ' comma var newstr = oldstr.replace (/\d+/g, ', '); Console.log (NEWSTR); = = a,b,c,d,//2. Regular matches to "all" number, replaced by: match result + ', ' comma newstr = oldstr.replace (/\d+/g, ' $&, '); Console.log (NEWSTR); = = a1,b2,c3,d4,//3. Regular matches to "all" numbers, each matching result calls the function and returns the replaced result newstr = Oldstr.replace (/\d+/g, function (word) {    if ( Word% 2 = = 0) {        return ' even ';    }    return ' odd ';}); Console.log (NEWSTR); + a odd B even c odd D even

4.9 Search (RegExp): Returns the position of the first match to find the regular expression

Parameters:

①regexp {regexp}: Regular expression. eg:/\d+/

return value:

{int} returns the position of the first matching result; 1 if no match is found

Example:

Console.log (' ABCD '. Search (/\d+/)); -1: No digital console.log (' abcd1234 '. Search (/\d+/)) was found; + 4: Position ordinal is 4, returns the position of the first digit

4.10 Slice (Start, |end): Returns a substring from the start position of the string to the previous position of end

Parameters:

①start {int}: The starting position index of the substring extraction (including the character at this location).

If the number is negative, the calculation starts at the end of the string. For example:-1 means the reciprocal of a string, and 2 represents the second-to-last character.

②end {int} optional: The end position index of the substring extraction (excluding characters at this location).

If the number is negative, the calculation starts at the end of the string. For example:-1 means the reciprocal of a string, and 2 represents the second-to-last character.

If this argument is omitted, all characters from the start position to the end are returned.

Attention:

The extraction order of the substring is left-to-right, and an empty string is returned if the start index position is greater than the end index position.

return value:

{string} returns a substring from the start position of the string to the previous position of end.

Example:

var s = ' ABCDEFG '; Console.log (S.slice (1)); BCDEFG: Omit end parameter, end position is end Console.log (S.slice (1, 3)); BC: Returns the substring Console.log (S.slice (-3)) from position ordinal 1 to position ordinal 2 (end previous position); EFG: Returns all characters Console.log (S.slice (-3,-1) from the third to the end of the countdown; EF: Returns all characters from the penultimate start to the second (end previous position)

4.11 Split (delimiter, |arraylength): Splits a string into an array of strings in a delimiter and returns

Parameters:

①delimiter {regexp | string}: The specified delimiter can be a regular expression or a string.

②arraylength {int} optional: The length of the split array. If omitted, all split substrings are returned.

Attention:

If the delimiter is in the first or last of the string, an empty string is added to the returned array.

return value:

{string[]} returns an array consisting of strings.

Example:

Console.log (' A,b,c,d,e '. Split (', ')); = = ["A", "B", "C", "D", "E"]console.log (', A,b,c,d,e, '. Split (', ') "); = = ["", "a", "B", "C", "D", "E", ""]: delimiter in the top or last side, an empty string Console.log (' a,b,c,d,e ') is added. Split (', ', 3)); = = ["A", "B", "C"]: Returns the first 3 split substring console.log (' a1b2c3d4e '. Split (/\d/)); = = ["A", "B", "C", "D", "E"]: Make a number as a delimiter

4.12 substr (Start, |wordlength): Returns a substring that is calculated from the start position of the string to a wordlength length

Parameters:

①start {int}: The starting position index of the substring extraction (including the character at this location).

If the number is negative, the calculation starts at the end of the string. For example:-1 means the reciprocal of a string, and 2 represents the second-to-last character.

②wordlength {int} optional: Extracts the length of the character. If this argument is omitted, all characters from the start position to the end are returned.

return value:

{string} returns the extracted string

Example:

Ar s = ' abcdefg '; Onsole.log (s.substr (0)); = =  ABCDEFG: Omit the second argument, return from position ordinal 0, one until the last character Onsole.log (s.substr (0, 3));//+ = ABC: Returns starting from position ordinal 0, Count of 3 characters Onsole.log (S.SUBSTR (2, 4)); = = Cdef: Returns starting from position ordinal 2, counting 4 characters Onsole.log (S.substr (-2, 3)); FG: Returns starting from the second-to-last string, counting 3 (more than the character length, returning only the statistical characters)

4.13 substring (start, |end): Returns a substring from the start position of the string to the previous position of end

Parameters:

①start {int}: The starting position index of the substring extraction (including the character at this location). Numbers cannot be negative, if negative number is treated as zero

②end {int} optional: The end position index of the substring extraction (excluding characters at this location). Numbers cannot be negative, if negative number is treated as zero

return value:

{string} returns a substring from the start position of the string to the previous position of end.

Example:

var s = ' ABCDEFG '; Console.log (s.substring (0)); = =  ABCDEFG: Omit the end parameter, return from position ordinal 0, until the last character Console.log (s.substring (0, 3));//= = ABC: returns from position ordinal 0 to position ordinal 2 ( The character of the previous ② parameter Console.log (s.substring (2, 4)); = = CD: Returns the character Console.log (S.substring (-3, 3) from the position ordinal 2 to the position ordinal 3 (the previous one of the ② parameters); ABC: If the parameter is negative, it is processed by the number zero, so this parameter actually returns the position ordinal 0 to the position ordinal 3 character

4.14 toUpperCase (): Converts a string to uppercase and returns 4.15 toLowerCase (): Converts the string to lowercase and returns 4.16 trim (): Removes the white space character at the beginning and end of the string and returns

================================== Series article ==========================================

This article: 3.6 JavaScript String Object

Web Development Road Series articles

JavaScript String Object

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.