Explanation of the attributes and methods of String objects of JavaScript native objects _ javascript skills

Source: Internet
Author: User
This article describes the attributes and methods of String objects of JavaScript native objects. This article describes the attributes and methods of length, charAt (), charCodeAt (), concat (), and indexOf (), lastIndexOf () and other method attributes. For more information, see Length

The length attribute returns the number of characters in a string.

Length is obtained based on the UTF-16 encoding of the string, the length of the Null String is 0. Length cannot be modified.

CharAt ()

The charAt () method returns characters at a specified position. Note that JavaScript does not have a character data type different from the string type, so the returned character is a string with a length of 1.

StringObject. charAt (index)

The index parameter is required. Represents the number at a certain position in the string, that is, the subscript of the character in the string. The subscript of the first character in the string is 0. If the index parameter is not between 0 and string. length, this method returns an empty string.

Note: The charAt () method may support non-BMP (Basic-Multilingual-Plane) characters. For more information, see MDN.

CharCodeAt ()

The charCodeAt () method returns the Unicode encoding of characters at the specified position. The returned value is an integer between 0 and 65535.
The charCodeAt () method is similar to the charAt () method, except that the former returns the encoding of the characters at the specified position, and the latter returns the character substrings.

StringObject. charCodeAt (index)

The index parameter is optional. Represents the number at a certain position in the string, that is, the subscript of the character in the string. The subscript of the first character in the string is 0. If the index is a negative number or is greater than or equal to the length of the string, charCodeAt () returns NaN. If the index is null, the default value is 0.

Unicode encoding ranges from 0 to 1,114,111. The first 128 Unicode encoding and ASCII character encoding match. The value returned by the charCodeAt () method is always less than 65536, because the characters with a higher value will appear in pairs and need to be retrieved at the same time using charCodeAt (I) and charCodeAt (I + 1.

Concat ()-Not recommended

The concat () method is used to connect two or more strings.

StringObject. concat (stringX, stringX ,..., StringX)

The stringX parameter is required. Is one or more string objects that will be connected to a string.

The concat () method converts all its parameters into strings, connects them to the end of the stringObject string in order, and returns the connected string. Note that the stringObject itself is not changed.

Note: we strongly recommend that you use the "+" operator to connect strings. This method is more efficient. For more information, see concat vs + vs join.
IndexOf ()

The indexOf () method returns the position of the first occurrence of a specified string value.

StringObject. indexOf (searchvalue, fromindex)

The searchvalue parameter is required and specifies the string value to be retrieved. The fromindex parameter is an optional integer. Specifies the position where the search starts in the string. The valid value is 0 to stringObject. length-1. If this parameter is omitted, It is retrieved from the first character of the string.

This method retrieves the stringObject string from start to end to see if it contains the searchvalue. The start position is at the string's fromindex or the start of the string (when fromindex is not specified ). If a searchvalue is found, the first position of the searchvalue is returned. The character position in stringObject starts from 0.

Note: The indexOf () method is case sensitive! If the string value to be retrieved does not appear, this method returns-1.

LastIndexOf ()

The lastIndexOf () method returns the last position of a specified string value and searches forward from the specified position in the string.

The lastIndexOf () and indexOf () parameters are consistent with the usage method, except that they are searched from the back to the front.

The Code is as follows:


Var str = "Hello world! "

Console. log (str. indexOf ("wo"); // 6
Console. log (str. indexOf ("wo", 2); // 6
Console. log (str. indexOf ("wo", 10); // 12
Console. log (str. lastIndexOf ("wo"); // 12
Console. log (str. lastIndexOf ("wo", 2); //-1
Console. log (str. lastIndexOf ("wo", 10); // 6

LocaleCompare ()

Compares two strings in a specific local order.

StringObject. localeCompare (target)

The target parameter is a required string to be compared with stringObject in a specific local order.

Returns the number of the comparison result. If stringObject is smaller than target, localeCompare () returns a number smaller than 0. If the value of stringObject is greater than target, this method returns a value greater than 0. If the two strings are equal or there is no difference according to the local sorting rules, this method returns 0.

When the <and> operators are applied to strings, they only use Unicode encoding to compare strings, regardless of local sorting rules. The order generated in this method is not necessarily correct. For example, in Spanish, the character "ch" is usually sorted as a character between the letter "c" and "d. The localeCompare () method provides the method for comparing strings, taking into account the default local sorting rules.

LocaleCompare () parameters in some advanced browsers also Support locales and options, refer to the following code and MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

The Code is as follows:


// Sorting rules for different cultures are different
Console. log ('ä'. localeCompare ('Z', 'de'); //-1
Console. log ('ä'. localeCompare ('Z', 'sv'); // 1

Match ()

The match () method can be used to search for a specified value in a string or to find a match between one or more regular expressions.

This method is similar to indexOf () and lastIndexOf (), but it returns the specified value rather than the position of the string.

StringObject. match (regexp)

The regexp parameter can be a string or a RegExp object of a regular expression.

Returns an array of matching results. The content of this array depends on whether regexp has a global flag.

If regexp does not mark g, the match () method can only perform one match in stringObject. If no matching text is found, match () returns null. Otherwise, it returns an array containing information related to the matched text it finds. The 0th elements in the array store the matching text, while the remaining elements store the text that matches the regular expression's subexpression. In addition to these regular array elements, the returned array also contains two object attributes. The index attribute declares the position of the starting character of the matching text in the stringObject, And the input attribute declares the reference to the stringObject.

If regexp has a flag, the match () method performs a global search and finds all matching substrings in stringObject. If no matched substring is found, null is returned. If one or more matched substrings are found, an array is returned. However, the content of the array returned by global match is very different from that returned by the former. Its array elements store all matched substrings in stringObject, and there is no index or input attribute.

Without the flag, stringObject. match (regexp) is the same as regexp.exe c (stringObject. In global search mode, match () does not provide text information that matches the subexpression, nor declare the position of each matched substring. You can use RegExp.exe c () to retrieve global information ().

Note: If you need to know whether a string matches a regular expression, use regexp. test (string). If you only want to match it once, use regexp.exe c (string) instead of string. match (regexp ).

The Code is as follows:


Var str = "Hello world! "
Var str2 = "1 plus 2 equal 3"

Console. log (str. match ("world"); // ["world", index: 6, input: "Hello world! "]
Console. log (str2.match (/\ d +/g); // ["1", "2", "3"]

Replace ()

The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression.

StringObject. replace (regexp/substr, replacement)

The regexp/substr parameter is required. Specifies the substring or RegExp object of the pattern to be replaced. If the value is a string, it is used as the direct text mode to be retrieved, rather than being converted to a RegExp object first. The replacement parameter is required. Is a string value. Specifies the function for replacing text or generating replacement text.

Method returns a new string, which is obtained after the first match or all matches of regexp are replaced by replacement.

The replace () method of the string stringObject performs the search and replace operation. It searches stringObject for substrings that match regexp and replaces them with replacement. If regexp has a global flag, the replace () method replaces all matched substrings. Otherwise, it only replaces the first matched substring.

Replacement can be a string or a function. If it is a string, each match will be replaced by a string. However, the $ character in replacement has a specific meaning. As shown below, it indicates that the string obtained from the pattern match will be used for replacement:

1. $-$
2. $ '-text on the left side of the matched substring.
3. $ '-text on the right of the matched substring.
4. $ &-substring that matches regexp.
5. $ number-text that matches the number subexpression in regexp.

Replacement can be a function. In this case, each matching call this function, and the string it returns will be used as the replacement text. The first parameter of this function is a matching string. The following parameter is a string that matches the subexpression in the pattern. There can be 0 or more such parameters. The following parameter is an integer that declares the position where the matching occurs in the stringObject. The last parameter is stringObject itself.

The Code is as follows:


// Replace Once
Var str = "Hello Microsoft! ";
Console. log (str. replace (/Microsoft/, "Google"); // Hello Google!
Console. log (str); // Hello Microsoft!

// Replace multiple times
Var str2 = "Hello Microsoft! And Microsoft! And Microsoft! Or Microsoft! ";
Console. log (str2.replace (/Microsoft/g, "Google"); // Hello Google! And Google! And Google! Or Google!

// Character conversion
Var str3 = "Doe, John ";
Console. log (str3.replace (/(\ w +) \ s *, \ s * (\ w +)/, "$2 $1"); // John Doe

Var str4 = '"a", "B "';
Console. log (str4.replace (/"([^"] *) "/g," '$ 1' "); // 'A',' B'

// Use the Function
Var str5 = 'aaa bbb ccc ';
Console. log (str5.replace (/\ B \ w + \ B/g, function (word ){
Return word. substring (0, 1). toUpperCase () + word. substring (1 );}
); // Aaa Bbb Ccc

Search ()

The search () method is used to retrieve the specified substring in a string or a substring that matches a regular expression.

StringObject. search (regexp)

The regexp parameter can be a substring to be retrieved in stringObject or a RegExp object to be retrieved.

Returns the starting position of the first substring matching regexp in stringObject. If no matched substring is found,-1 is returned.

Note: The search () method does not perform global match, and the flag is ignored. It also ignores the lastIndex attribute of regexp and always searches from the start of the string, which means it always returns the first matching position of stringObject.

The Code is as follows:


Var str = "Hello Microsoft! ";
Console. log (str. search (/Microsoft/); // 6

If you only want to know whether a matched string exists, use the search () method and the test () method. If you want more information, you can use the match () and exec () methods, but the efficiency is low.

Slice ()

The slice () method can extract a part of a string and return the extracted part with a new string.

StringObject. slice (start, end)

The start parameter is the starting subscript of the part to be extracted. If it is a negative number, this parameter specifies the position starting from the end of the string. That is to say,-1 refers to the last character of the string,-2 refers to the second to last character, and so on.

The end parameter is the subscript next to the end of the clip to be extracted. If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If this parameter is a negative number, it specifies the position starting from the end of the string.

Method returns a new string. It contains all the characters starting from start (including start) to end (excluding end) of the stringObject string.

Note: The methods slice (), substring (), and substr () of the String object can return the specified part of the String. We strongly recommend that you use the slice () method in all scenarios.

The Code is as follows:


Var str = "Hello Microsoft! ";
Console. log (str. slice (6); // Microsoft!
Console. log (str. slice (6, 12); // Micros

Substring ()

We recommend that you use slice () instead of slice.

Substr ()

We recommend that you use slice () instead of slice.

ToLocaleLowerCase ()

It is not recommended. It is only useful in Turkish and other minority languages. toLowerCase () is recommended.

ToLocaleUpperCase ()

It is not recommended. It is only useful in Turkish and other minority languages. We recommend that you use toUpperCase () instead.

ToLowerCase ()

The toLowerCase () method is used to convert a string to lowercase.

ToUpperCase ()

The toUpperCase () method is used to convert a string to uppercase.

The String object also has many methods for HTML tags: anchor (), big (), blink (), bold (), fixed (), fontcolor (), fontsize () italics (), link (), small (), strike (), sub (), and sup (). They are mainly HTML formatting for String objects, and few of them are applied now, which is not recommended.

Example of method Demonstration:

The Code is as follows:



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.