In-depth exploration of JavaScript String objects

Source: Internet
Author: User

In-depth exploration of JavaScript String objects

This article gives you a detailed introduction to the String object in javascript, the definition method, instance attributes, and instance methods. It is very detailed and comprehensive. I would like to recommend it to you and hope it will help you.

 

 

String object

1. Introduction

String object to operate on strings, such as intercepting a substring, searching for strings/characters, and converting uppercase and lowercase letters.

2. Definition Method

2.1 new String (Value) constructor: returns a String object whose content is Value.
Parameters:

① Value {String}: String

Return Value:

{String object} returns a String object whose content is Value.

Example:

 

The Code is as follows:


Var demoStr = new String ('abc ');
Console. log (typeof demoStr); // => object
Console. log (demoStr); // => abc

 

2.2 direct assignment (recommended)
Example:

 

The Code is as follows:


Var demoStr = 'abc ';
Console. log (typeof demoStr); // string
Console. log (demoStr); // => abc

 

3. instance attributes

3.1 length: returns the number of characters in the string.

 

The Code is as follows:


Var s = 'abc ';
Console. log (s. length); // => 3
Console. log ('Happy New Year'. length); // => 4: a Chinese character is also counted as one count
Console. log (''. length); // => 0: Null String returns 0

 

4. instance method

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

4.1 charAt (index): returns the character at the specified position in a string starting from 0. If a nonexistent value is input, an empty string is returned.
Parameters:

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

Return Value:

{String} returns the character at the specified position in a string. If a nonexistent position value is input, an empty string is returned.

Example:

 

The Code is as follows:


Var s = 'abc ';
Console. log (s. charAt (1); // => B: The Return position is 1.
Console. log (s); // => does not affect the original array
Console. log (s. charAt (5); // => '': returns a null string with a length of 0.

 

4.2 charCodeAt (index): returns the Unicode encoding of characters at the specified position in a string.
Parameters:

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

Return Value:

{Number} returns the Unicode encoding of the specified position character in a string. If a nonexistent position value is input, NaN is returned.

Example:

 

The Code is as follows:


Var s = 'abc ';
Console. log (s. charCodeAt (0); // => 98: Unicode encoding of character B
Console. log (s. charCodeAt (5); // => NaN: returns NaN

 

4.3 concat (value1, value2... valueN): connects one or more strings and returns the connected strings.
Parameters:

① Value1, value2... valueN {string}: one or more strings

Return Value:

{String} returns the connected string.

Example:

 

The Code is as follows:


Var s = 'abc ';
Console. log (s. concat ('D'); // => abcd
Console. log (s); // => abc: the original string is not affected.
Console. log (s. concat ('D', 'E'); // => abcde

 

4.4 indexOf (value, | startPosition): searches for a string or character in the instance from the beginning to the end, and returns the found position (counting from 0 ). If not found,-1 is returned.
Parameters:

① Value {string}: The searched string

② StartPosition {int} (optional) Start position of the start position. The default position is 0.

Return Value:

{Int} returns the position found (counting starts from 0 ). If not found,-1 is returned.

Example:

 

The Code is 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: Search from location 2 (3rd characters)

 

4.5 lastIndexOf (value, | startPosition): searches for a string or character from the back to the back of the instance, and returns the found position (counting from 0 ). If not found,-1 is returned.
Parameters:

① Value {string}: The searched string

② StartPosition {int} (optional) Start position of the start position. The default start position is the last position.

Return Value:

{Int} returns the position found (counting starts from 0 ). If not found,-1 is returned.

Example:

 

The Code is as follows:


Var s = 'abc ';
Console. log (s. lastIndexOf ('A'); // => 3: search from the back
Console. log (s. lastIndexOf ('D'); // =>-1: Return-1 not found
Console. log (s. lastIndexOf ('A', 2); // => 0: search forward from position 2 (3rd characters)

 

4.6 localeCompare (value): Compare the instance with the parameter and return the comparison result.
Parameters:

① Value {string}: string to be compared

Return Value:

0: The instance is larger than the Parameter

1: instances and parameters are equal

-1: The instance is smaller than the Parameter

Example:

 

The Code is as follows:


Var s = 'abc ';
Console. log (s. localeCompare ('AB'); // => 1: The instance is larger than the Parameter
Console. log (s. localeCompare ('abc'); // => 0: The instance is equal to the parameter
Console. log (s. localeCompare ('abd'); // =>-1: The instance is smaller than the Parameter

 

4.7 match (regexp): Use a regular expression for matching search
Parameters:

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

Return Value:

Returns different results based on whether the regular expression has the attribute 'G'. If no match is found, {null} is returned }:

① If the regular expression does not contain the 'G' attribute, a match is executed and {single match} result object is returned. The object contains the following attributes:

Array serial number: indicates the matching result. 0 indicates the matching text, 1 indicates the matching result from the right 1st parentheses, 2 indicates the second parentheses, and so on.

Index attribute: indicates the starting position of the matching text in the matching source.

Input attribute: indicates the matching source.

② The regular expression carries the attribute 'G', performs global matching, finds all matching objects of the string, and returns a {string Array}: the array element contains every matching object in the string, does not contain strings in the regular expression brackets, nor provides the index and input attributes.

Example:

 

The Code is as follows:


// 1. Single Match
Var s = 'a1b2c3d4 ';
Var mc = s. match (/\ d +/); // => get the result of the first regular match
If (mc! = Null ){
Console. log (mc. index); // => 1: The matching result is at the starting position of the matching source.
Console. log (mc. input) // => a1b2c3d4: match source
Console. log (mc [0]); // => 1: Obtain the matching result.
}
// 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: Obtain matching results
}
}
// 3. Matching with parentheses
S = 'a1b2c3d4 ';
Mc = s. match (/[a-z] ([1-9])/); // => obtain the result of the first regular match
If (mc! = Null ){
Console. log (mc. index); // => 0: the matching result is at the starting position of the matching source.
Console. log (mc. input) // => a1b2c3d4: match source
Console. log (mc [0]); // => a1: serial number 0 indicates the matched result.
Console. log (mc [1]); // => 1: Serial Number 1 indicates the child matching result in the first bracket.
}

 

4.8 replace (regexp, replaceStr): replace the substring matched by the regular expression and return the replaced string.
Parameters:

① Regexp {regexp}: regular expression. Eg:/\ d +/

② ReplaceStr {string | function }:

1) if it is a string, it indicates the string to be replaced, and all matching strings are replaced with this string;

The $ character in the string has a special meaning:

$1, $2... $99: indicates the matching subitem of the ① parameter from left to right parentheses

$ &: Indicates the subitem that the entire ① parameter matches

$: Dollar sign

2) if it is a function, this function is called for each matching result. The unique parameter of the function is the matching result and a replacement result is returned.

Return Value:

{String} returns a replaced string.

Example:

 

The Code is as follows:


Var oldStr = 'a1b2c3d4 ';
// 1. Match the regular expression with the [all] Number and replace it with ',' Comma
Var newStr = oldStr. replace (/\ d +/g ,',');
Console. log (newStr); // => a, B, c, d,
// 2. Replace the regular expression with the [all] number with the matching result + ', 'comma
NewStr = oldStr. replace (/\ d +/g, '$ &,');
Console. log (newStr); // => a1, b2, c3, d4,
// 3. The regular expression matches the [all] number. The function is called for each matching result and the replaced result is returned.
NewStr = oldStr. replace (/\ d +/g, function (word ){
If (word % 2 = 0 ){
Return 'even ';
}
Return 'Qi ';
});
Console. log (newStr); // => a odd B even c odd d Even

 

4.9 search (regexp): returns the first matched position of the regular expression.
Parameters:

① Regexp {regexp}: regular expression. Eg:/\ d +/

Return Value:

{Int} returns the position of the first matched result. If no matching result is found,-1 is returned.

Example:

 

The Code is as follows:


Console. log ('abc'. search (/\ d +/); // =>-1: No number found
Console. log ('abc1234'. search (/\ d +/); // => 4: The position number is 4, and the position of the first digit is returned.

 

4.10 slice (start, | end): returns the substring from the start position of the string to the previous position of end.
Parameters:

① Start {int}: Index of the start position of the substring extraction (including the characters at this position ).

If the number is negative, it is calculated from the end of the string. For example,-1 indicates the last string, and-2 indicates the second to the last.

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

If the number is negative, it is calculated from the end of the string. For example,-1 indicates the last string, and-2 indicates the second to the last.

If this parameter is omitted, all characters from start to end are returned.

Note:

The substring is extracted from left to left. If the start index position is greater than the end index position, an empty string is returned.

Return Value:

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

Example:

 

The Code is as follows:


Var s = 'abcdefg ';
Console. log (s. slice (1); // bcdefg: the end parameter is omitted and the end position is the end
Console. log (s. slice (1, 3); // bc: return the substring from position 1 to position 2 (prior to end)
Console. log (s. slice (-3); // efg: returns all characters starting from the last three to the end.
Console. log (s. slice (-3,-1); // ef: returns all characters from the last three to the second (the position before the end ).

 

4.11 split (delimiter, | arrayLength): Splits a string into an array consisting of strings according to certain delimiters and returns
Parameters:

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

② ArrayLength {int} (optional) Length of the split array. If omitted, all split substrings are returned.

Note:

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

Return Value:

{String []} returns an array composed of strings.

Example:

 

The Code is 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", ""]: the separator is at the beginning or end, and an empty string is added.
Console. log ('a, B, c, d, e '. split (',', 3); // => ["a", "B", "c"]: returns the first three substrings.
Console. log ('a1b2c3d4e '. split (/\ d/); // => ["a", "B", "c", "d", "e"]: use numbers as separators

 

4.12 substr (start, | wordLength): returns a substring of the length calculated from the start position of the string to wordLength.
Parameters:

① Start {int}: Index of the start position of the substring extraction (including the characters at this position ).

If the number is negative, it is calculated from the end of the string. For example,-1 indicates the last string, and-2 indicates the second to the last.

② WordLength {int} (optional) Length of extracted characters. If this parameter is omitted, all characters from start to end are returned.

Return Value:

{String} returns the extracted string.

Example:

 

The Code is as follows:


Ar s = 'abcdefg ';
Onsole. log (s. substr (0); // => abcdefg: The second parameter is omitted, and the character starting from position 0 to the end is returned.
Onsole. log (s. substr (0, 3); // => abc: returns the value starting from position 0 and counting 3 characters.
Onsole. log (s. substr (2, 4); // => cdef: returns four characters starting from position 2.
Onsole. log (s. substr (-2, 3); // fg: returns three counts starting from the second to the last string (if the length is exceeded, only the statistical characters are returned)

 

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

① Start {int}: Index of the start position of the substring extraction (including the characters at this position ). The number cannot be negative. If the number is negative, the value is 0.

② End {int} (optional) end position index of the substring extraction (excluding characters at this position ). The number cannot be negative. If the number is negative, the value is 0.

Return Value:

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

Example:

 

The Code is as follows:


Var s = 'abcdefg ';
Console. log (s. substring (0); // => abcdefg: the end parameter is omitted, and the character starting from position 0 to the end is returned.
Console. log (s. substring (0, 3); // => abc: returns the character from position 0 to position 2 (prior to ②)
Console. log (s. substring (2, 4); // => cd: returns the character from position 2 to position 3 (prior to parameter ②)
Console. log (s. substring (-3, 3); // abc: If the parameter is negative, it is processed by number 0. Therefore, this parameter returns the characters from position 0 to position 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 spaces at the beginning and end of a string and returns

The above is all the content of this article. We hope that you will have a new understanding of the String object in javascript through this 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.