Delve into JavaScript string objects _ Basics

Source: Internet
Author: User
Tags instance method

String String Object

1. Introduce

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

2. How to define

2.1 New String (value) constructor: Returns a String object that contains Value
Parameters:

①value {string}: String

return value:

{String Object} returns a string object with the content of value

Example:

Copy Code code as follows:

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

2.2 Direct Assignment (recommended)
Example:

Copy Code code as follows:

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

3. Instance Properties

3.1 Length: Returns the number of characters in a string

Copy Code code as follows:

var s = ' abc ';
Console.log (s.length); => 3
Console.log (' Happy New Year '. length); => 4: A Chinese character is also calculated as 1 quantity
Console.log (". Length"); => 0: empty string return 0

4. Instance method

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 a character at a specified position in a string, starting at 0 and returning an empty string if a nonexistent number is passed in
Parameters:

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

return value:

{string} returns the character at the specified position in a string, or returns an empty string if the value of a nonexistent location is passed in

Example:

Copy Code code as follows:

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

4.2 charCodeAt (Index): Returns a Unicode encoding for a specified position character in a string
Parameters:

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

return value:

{Number} returns a Unicode encoding of the specified position character in a string; If you pass in a nonexistent position value, return Nan

Example:

Copy Code code as follows:

var s = ' abc ';
Console.log (s.charcodeat (0)); => 98: Unicode encoding for character B
Console.log (S.charcodeat (5)); => nan: Gets a character that does not exist in the position, returns Nan

4.3 concat (Value1,value2 ... valuen): Connect 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:

Copy Code code as follows:

var s = ' abc ';
Console.log (S.concat (' d ')); => ABCD
Console.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 instance in the past and returns the location found (counting from 0). If not found, return-1
Parameters:

①value {string}: Found string

②startposition {int} Optional: Start lookup starting position, default from location 0

return value:

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

Example:

Copy Code code as follows:

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

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

①value {string}: Found string

②startposition {int} Optional: Start lookup starting position, default start from last

return value:

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

Example:

Copy Code code as follows:

var s = ' abcabc ';
Console.log (S.lastindexof (' a ')); => 3: Looking forward from the back
Console.log (S.lastindexof (' d ')); =>-1: Not Found return-1
Console.log (S.lastindexof (' A ', 2)); => 0: Start looking forward from position 2 (3rd character)

4.6 Localecompare (value): instance compares with parameters, returns the result of comparison
Parameters:

①value {string}: String to compare

return value:

0: The case is larger than the parameter

1: the instance is equal to the parameter

-1: the instance is smaller than the parameter

Example:

Copy Code code as follows:

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: the instance is smaller than the parameter
 

4.7 Match (regexp): matching lookup using regular expressions
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 there is no match:

① a regular expression without attribute ' G ', performs a match, returns a {single matching} result object that contains the following properties:

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

Index property: Represents the match text at the beginning of the matching source

Input property: representing matching source

② Regular expression with 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 string, does not contain strings in regular expression brackets, and does not provide index and input properties.

Example:

Copy Code code as follows:

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 start of the matching source
Console.log (mc.input)//=> a1b2c3d4: Matching source
Console.log (Mc[0]); => 1: Get the results that match
}
2. Global match
var Mcarray = S.match (/\d+/g); => get all regular matching 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: Get the result that matches
}
}
3. Parenthesized Matching
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 start of the matching source
Console.log (mc.input)//=> a1b2c3d4: Matching source
Console.log (Mc[0]); => A1: Ordinal 0 Indicates the result of the match
Console.log (mc[1]); => 1: Ordinal 1 represents the result of a child match within the first parenthesis
}

4.8 Replace (RegExp, REPLACESTR): Replaces a regular expression-matched substring and returns the replaced string
Parameters:

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

②replacestr {string | function}:

1 if the string, which represents the replacement of the string, matching to the string are replaced with this character;

The $ character in the string has a special meaning:

$1,$2. $99: A matching subkey representing the left to right parenthesis of a ① parameter

$&: A subkey that represents the matching of the entire ① parameter

$$: Dollar sign

2 If the function, means that each match result calls this function, the function's unique parameter is the match result, and returns a substitution result.

return value:

{string} returns a replacement string

Example:

Copy Code code as follows:

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 match to "all" number, replace with: 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 result of the replacement
Newstr = Oldstr.replace (/\d+/g, function (word) {
if (word% 2 = 0) {
return ' I ';
}
return ' odd ';
});
Console.log (NEWSTR); => a odd B-odd D-pair

4.9 Search (RegExp): Returns the position where the first match of the regular expression is found
Parameters:

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

return value:

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

Example:

Copy Code code as follows:

Console.log (' ABCD '. Search (/\d+/)); =>-1: No numbers found
Console.log (' abcd1234 '. Search (/\d+/)); => 4: The position ordinal number 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
Parameters:

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

If the number is negative, the calculation begins at the end of the string. For example:-1 represents the penultimate string,-2 represents the penultimate character.

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

If the number is negative, the calculation begins at the end of the string. For example:-1 represents the penultimate string,-2 represents the penultimate character.

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

Attention:

The order in which the substring is fetched is from left to there, 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.

Example:

Copy Code code as follows:

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

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

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

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

Attention:

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

return value:

{string[]} returns an array of strings.

Example:

Copy Code code as follows:

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", "" "]: Separator at the top or last side, an empty string is added
Console.log (' A,b,c,d,e '. Split (', ', 3)); => ["A", "B", "C"]: Returns the first 3 split substrings
Console.log (' a1b2c3d4e '. Split (/\d/)); => ["A", "B", "C", "D", "E"]: a number as a separator

4.12 substr (Start, |wordlength): Returns a substring that starts at the start of the string and computes 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 begins at the end of the string. For example:-1 represents the penultimate string,-2 represents the penultimate character.

②wordlength {int} optional: Extracts the length of a 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:

Copy Code code as follows:

Ar s = ' ABCDEFG ';
Onsole.log (s.substr (0)); => ABCDEFG: Omit the second argument and return to the last character starting at position ordinal 0
Onsole.log (S.substr (0, 3)); => ABC: Return starting from position ordinal 0, counting 3 characters
Onsole.log (S.substr (2, 4)); => Cdef: Return starting from position ordinal 2, counting 4 characters
Onsole.log (S.substr (-2, 3)); FG: Returns from the penultimate string, counting 3 (longer than the character length, returning only the counted characters)

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

①start {int}: The starting position index of the substring extraction, including the character at this location. Number cannot be negative, if negative, press 0来 to handle

②end {int} optional: The end position index of the substring extraction (excluding characters from this location). Number cannot be negative, if negative, press 0来 to handle

return value:

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

Example:

Copy Code code as follows:

var s = ' ABCDEFG ';
Console.log (s.substring (0)); => ABCDEFG: Omit the end argument and return to the last character starting at position ordinal 0
Console.log (s.substring (0, 3)); => ABC: Returns the character from the position ordinal 0 to the position ordinal 2 (the previous one of the ② parameter)
Console.log (S.substring (2, 4)); => CD: Returns a character from the position ordinal 2 to the position ordinal 3 (the previous one of the ② parameter)
Console.log (S.substring (-3, 3)); ABC: If the parameter is negative, it is processed numerically 0来, so this parameter actually returns the character of position ordinal 0 to position ordinal 3

4.14 toUpperCase (): Converts a string to uppercase and returns
4.15 touppercase (): Converts a string to lowercase and returns
4.16 Trim (): Removes white space characters at the beginning and end of a string and returns

The above is the entire content of this article, I hope that through this article, you can have a new understanding of the string object in JavaScript.

Related Article

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.