The properties and methods of the string object of JavaScript native object _javascript tips

Source: Internet
Author: User
Tags deprecated html tags lowercase

Length

The Length property can return the number of characters in the string.

Length is obtained based on the UTF-16 encoding of the string, with an empty string length of 0. Length is not modifiable.

CharAt ()

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

Stringobject.charat (Index)

Parameter index is required. A number that represents a position in a string, that is, the subscript of a character in a string. The subscript for the first character in the string is 0. If the argument index is not between 0 and String.Length, the method returns an empty string.

Note: the CharAt () method is problematic for some non-BMP (Basic-multilingual-plane) character support, as reference: MDN

charCodeAt ()

The charCodeAt () method returns the Unicode encoding of the character at the specified position. This return value is an integer between the 0–65535.
The method charCodeAt () is similar to the operation performed by the CharAt () method, except that the former returns the encoding of the character at the specified position, and the latter returns a string of characters subcode.

Stringobject.charcodeat (Index)

Parameter index is optional. A number that represents a position in a string, that is, the subscript of a character in a string. The subscript for the first character in the string is 0. If index is a negative number, or is greater than or equal to the length of the string, charCodeAt () returns NaN. The default is 0 when index is empty.

The Unicode encoding ranges from 0 to 1,114,111. The first 128 Unicode encodings and ASCII character encodings match. The charCodeAt () method returns a value that is always less than 65536 because a higher-value word Fu Huicheng appears, and needs to be retrieved simultaneously with 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)

Parameter STRINGX is required. is one or more string objects that will be concatenated to a string.

The concat () method converts all its arguments to strings and then sequentially connects to the tail of the string stringobject and returns the concatenated string. Please note that the Stringobject itself has not been changed.

Note that it is highly recommended that you use the "+" operator for string concatenation to override this method and be more efficient, for reference: Concat vs + vs Join.
indexOf ()

The IndexOf () method returns the location of the first occurrence of a specified string value in a string.

Stringobject.indexof (Searchvalue, Fromindex)

Parameter searchvalue is required to specify the string value to retrieve. The parameter fromindex is an optional integer parameter. Specify where to start retrieving in the string. Its legal value is 0 to stringobject.length–1. If this argument is omitted, it is retrieved from the first character of the string.

This method retrieves the string stringobject from beginning to end to see if it contains substring searchvalue. The location at which to start retrieving is at the fromindex of the string or at the beginning of the string (no fromindex is specified). If a searchvalue is found, it returns the position of the first occurrence of searchvalue. The character position in the Stringobject is starting at 0.

Note: the IndexOf () method is case sensitive! If the string value to retrieve does not appear, the method returns-1.

LastIndexOf ()

The LastIndexOf () method returns the last occurrence of a specified string value, which is searched forward at the specified position in a string.

The LastIndexOf () and indexOf () parameters are consistent with the use method, except that they are searched backwards.

Copy Code code as follows:

var str= "Hello World 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 local-specific order.

Stringobject.localecompare (target)

Parameter target is a required string to compare with Stringobject in a local-specific order.

Returns the number of the result of the comparison. If Stringobject is less than target, Localecompare () returns a number less than 0. If the stringobject is greater than target, the method returns a number greater than 0. If two strings are equal, or if there is no difference based on the local collation, the method returns 0.

When the < and > operators are applied to strings, they compare strings only with Unicode encoding of characters, regardless of the local collation. The order generated in this way is not necessarily correct. For example, in Spanish, the character "ch" is usually sorted as a character that appears between the letter "C" and "D". The Localecompare () method provides a method for comparing strings, taking into account the default local collation.

Localecompare () The 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

Copy Code code as follows:

Different sorting rules of culture
Console.log (' Ä '. Localecompare (' z ', ' de ')); -1
Console.log (' Ä '. Localecompare (' z ', ' SV ')); 1

Match ()

The match () method retrieves the specified value within a string, or finds a match for one or more regular expressions.

The method is similar to IndexOf () and LastIndexOf (), but it returns the specified value, not the position of the string.

Stringobject.match (RegExp)

Parameter RegExp can be either a string or a regular expression RegExp object.

Returns an array that holds the matching results. The contents of the array depend on whether RegExp has global flag G.

If RegExp does not have a flag G, then the match () method can only perform a match in Stringobject. If no matching text is found, match () returns NULL. Otherwise, it returns an array that holds information about the matching text it finds. The No. 0 element of the array holds the matching text, while the remaining elements hold the text that matches the subexpression of the regular expression. In addition to these regular array elements, the returned array also contains two object properties. The Index property declares the position of the starting character of the matching text in the Stringobject, and the input property declares a reference to the Stringobject.

If the regexp has a flag G, the match () method performs a global search and finds all the matching substrings in the stringobject. If no matching substring is found, NULL is returned. If one or more matching substrings are found, an array is returned. However, the contents of the array returned by the global match are very different from the former, and its array elements contain all the matching substrings in the stringobject, and there is no index attribute or input property.

No flag g, call Stringobject.match (regexp) and call Regexp.exec (Stringobject) the same result. In global retrieval mode, match () does not provide information about the text that matches the subexpression, nor does it declare the position of each matching substring. You can use Regexp.exec () If you need information for these global searches.

Note: If you need to know whether a string matches a regular expression, use Regexp.test (string), or use Regexp.exec (string) instead of String.match (regexp) If you want to match only once.

Copy Code code 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 replaces some characters in a string with some other characters, or replaces a substring that matches a regular expression.

Stringobject.replace (REGEXP/SUBSTR, replacement)

Parameter regexp/substr is required. The RegExp object that prescribes the substring or pattern to be replaced. If the value is a string, it is used as the direct text pattern to retrieve, not first converted to the RegExp object. Parameter replacement is required. is a string value. Provides a function that replaces text or generates alternate text.

method returns a new string that is replaced with replacement with the first match of RegExp or all matches.

The replace () method of the string Stringobject performs a find-and-replace operation. It will look for substrings in the stringobject that match the regexp, and then replace them with replacement. If RegExp has global flag G, then the Replace () method replaces all matching substrings. Otherwise, it replaces only the first matching substring.

Replacement can be either a string or a function. If it is a string, then each match is replaced by a string. However, the $ character in replacement has a specific meaning. As shown below, it shows that the string that is matched from the pattern will be used to replace:

1.$$–$
2.$ '-text located on the left side of the matching substring.
3.$ '-text located on the right side of the matching substring.
4.$&-a substring that matches the regexp.
5. $number-Text that matches the number of regexp in the

Replacement can be a function, in which case each match calls the function, and the string it returns is used as the replacement text. The first parameter of the function is a string that matches the pattern. The next argument is a string that matches the subexpression in the pattern, and can have 0 or more of these parameters. The next argument is an integer that declares where the match appears in the Stringobject. The last parameter is the stringobject itself.

Copy Code code 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 conversions
var str3 = "Doe, John";
Console.log (Str3.replace (\w+) \s*, \s* (\w+)/, "$ $")); John Doe

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

Working with functions
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 retrieves the substring specified in the string, or retrieves a substring that matches the regular expression.

Stringobject.search (RegExp)

The parameter RegExp can be a substring that needs to be retrieved in Stringobject, or a RegExp object that needs to be retrieved.

Returns the starting position of the first substring in the stringobject that matches the regexp. Returns-1 if no matching substring is found.

Note: The search () method does not perform a global match, and it ignores flag g. It ignores the RegExp lastindex property at the same time and always retrieves it from the beginning of the string, which means it always returns the first matching position of Stringobject.

Copy Code code as follows:

var str = "Hello microsoft!";
Console.log (Str.search (/microsoft/)); 6

If you just want to know if there is a matching string, use Search () and use the test () method almost. If you want more information, you can use the match () and the Exec () method, but the efficiency is low.

Slice ()

The slice () method extracts a part of the string and returns the extracted part with a new string.

Stringobject.slice (start, end)

Parameter start is the starting subscript of the fragment to be extracted. If it is a negative number, the parameter sets the position from the tail of the string. In other words,-1 refers to the last character of the string,-2 to the penultimate character, and so on.

The parameter end is the subscript immediately following the ending of the fragment to be extracted. If this parameter is not specified, the substring to be fetched includes the string at the end of the original string. If the argument is a negative number, it sets the position from the tail of the string.

method returns a new string. Includes all characters for the string stringobject from start (including start) to end ending (excluding ends).

Note: The method slice (), substring (), and substr () of the string object can return the specified portion of the string. It is strongly recommended that the slice () method be used on all occasions.

Copy Code code as follows:

var str = "Hello microsoft!";
Console.log (Str.slice (6)); microsoft!
Console.log (Str.slice (6, 12)); Micros

SUBSTRING ()

Deprecated, it is recommended to use slice () instead.

SUBSTR ()

Deprecated, it is recommended to use slice () instead.

toLocaleLowerCase ()

Deprecated, only useful in a few languages, such as Turkish, and is recommended for use with toLowerCase () substitution.

toLocaleUpperCase ()

Deprecated, only useful in a few languages, such as Turkish, and is recommended for use with touppercase () substitution.

toLowerCase ()

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

toUpperCase ()

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

A string object also has a number of methods for HTML tags: anchor (), Big (), Blink (), bold (), fixed (), FontColor (), FontSize (), italics (), link (), Small (), Strike (), sub (), SUP (). They are primarily HTML formatted for String objects and are now rarely applied and deprecated.

Method Demo instance:

Copy Code code as follows:

<body>

<script type= "Text/javascript" >

var txt= "Hello world!"

document.write ("<p>big:" + txt.big () + "</p>")
document.write ("<p>small:" + txt.small () + "</p>")

document.write ("<p>bold:" + txt.bold () + "</p>")
document.write ("<p>italic:" + txt.italics () + "</p>")

document.write ("<p>blink:" + txt.blink () + "(does not work in IE) </p>")
document.write ("<p>fixed:" + txt.fixed () + "</p>")
document.write ("<p>strike:" + txt.strike () + "</p>")

document.write ("<p>fontcolor:" + txt.fontcolor ("Red") + "</p>")
document.write ("<p>fontsize:" + txt.fontsize + "</p>")

document.write ("<p>lowercase:" + txt.tolowercase () + "</p>")
document.write ("<p>uppercase:" + txt.touppercase () + "</p>")

document.write ("<p>subscript:" + txt.sub () + "</p>")
document.write ("<p>superscript:" + txt.sup () + "</p>")

document.write ("<p>link:" + txt.link ("http://www.w3school.com.cn") + "</p>")
</script>

</body>

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.