JS String Method __js

Source: Internet
Author: User
Tags comments numeric value

JavaScript String Object Reference Manual

1.String objects
A string object is used to process text (strings).

To create the syntax for a String object:
New String (s);
String (s);
The parameter S is the value to be stored in the string object or converted to the original string.

return value
When string () and operator new are used together as constructors, it returns a newly created string object that holds a string representation of the string s or S.
When a string () is invoked without the new operator, it converts only s to the original string and returns the converted value.

2.String Object Properties: Length ()
The Length property can return the number of characters in the string.
Instance
<script type= "Text/javascript" >
var txt= "Hello world!"
document.write (Txt.length)
</script>
Output:
12

3. Some control methods of the style:
Big (): Displays a string in a large font, such as "Hello world!". Big ()
Blink (): Displays a flashing string that is not available for work in Internet Explorer.
Bold (): Displays a string using bold.
Italics (): Displays a string using italic.
Small (): Displays a string using a small font size.
Strike (): Use strikethrough to display strings.
Sub (): Displays the string as subscript.
SUP (): Displays the string as superscript.
toLowerCase (): Converts a string to lowercase.
toUpperCase (): Converts a string to uppercase.
Fixed (): Displays a string in typewriter text.
FontColor (): Displays a string using the specified color.
FontSize (): Displays a string using the specified dimensions.
Link (): Used to display strings as hyperlinks, such as: "Baidu". Link ("http://www.baidu.com")

4.anchor ()
Definitions and usage
The anchor () method is used to create the HTML anchor, Stringobject.anchor (Anchorname)
Instance
<script type= "Text/javascript" >
var txt= "Hello world!"
document.write (Txt.anchor ("Myanchor"))
</script>
The above code will output as pure HTML:
<a name= "Myanchor" >hello world!</a>

5.charAt ()
Definitions and usage
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.

Syntax: Stringobject.charat (index) parameter description
Index required. A number that represents a position in a string, that is, the subscript of a character in a string.
Note: 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.

Instance
<script type= "Text/javascript" >
var str= "Hello world!"
document.write (Str.charat (1))
</script>
The output of the above code is: E

6.concat ()
Definition and Usage: the Concat () method is used to concatenate two or more strings.
Grammar
Stringobject.concat (stringx,stringx,..., stringx) parameter description, STRINGX required. 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.
Stringobject.concat () is very similar to Array.concat ().
Tip: Note that it is usually easier to use the "+" operator for concatenation of strings.

Instance
<script type= "Text/javascript" >
var str1= "Hello"
var str2= "world!"
document.write (Str1.concat (STR2))
</script>
The output of the above code is: Hello world!

7.indexOf ()
Definition and Usage: the IndexOf () method returns the location of the first occurrence of a specified string value in a string.
Syntax: Stringobject.indexof (searchvalue,fromindex) parameter description
Searchvalue required. A string value that requires retrieval.
Fromindex 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.
Note: the IndexOf () method is case sensitive.
Note: If the string value to retrieve does not appear, the method returns-1.

Instance
<script type= "Text/javascript" >
var str= "Hello world!"
document.write (Str.indexof ("Hello") + "<br/>")
document.write (Str.indexof ("World") + "<br/>")
document.write (Str.indexof ("World"))
</script>
Output of the above code: 0, -1,6

8.lastIndexOf ()
Introduction to the same indexof ()
Instance
<script type= "Text/javascript" >
var str= "Hello world!"
document.write (Str.lastindexof ("Hello") + "<br/>")
document.write (Str.lastindexof ("World") + "<br/>")
document.write (Str.lastindexof ("World"))
</script>
Output of the above code: 0,-1,6

9.localeCompare ()
Definition and Usage: compare two strings in a local-specific order.
Grammar:
Stringobject.localecompare (target) parameter description
A string that the target will compare to Stringobject in a local-specific order.

return value
A number that describes 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.

Description
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. The ECMAscript standard does not specify how to perform a local-specific comparison operation, which only requires that the function take the sort rules provided by the underlying operating system.
Instance
var str;
Str.sort (
function (a,b) {
return A.localecompare (b)
}
)

10.match ()
Definitions and usage
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.

Grammar
Stringobject.match (Searchvalue)
Stringobject.match (RegExp)
Parameter description: Searchvalue required. Specify the string value to retrieve.
RegExp required. The RegExp object that prescribes the pattern to match. If the parameter is not a RegExp object, you need to pass it to the RegExp constructor first and convert it to a RegExp object.

return value
An array that holds the matching results. The contents of the array depend on whether RegExp has global flag G.
Description
The match () method retrieves the string stringobject to find one or more text that matches the regexp. The behavior of this method depends to a great extent on whether the regexp has a sign 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.
Note: 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. If you need information for these global searches, you can use Regexp.exec ().

Example 1
<script type= "Text/javascript" >
var str= "Hello world!"
document.write (Str.match ("World") + "<br/>")
document.write (Str.match ("World") + "<br/>")
document.write (Str.match ("worlld") + "<br/>")
document.write (Str.match ("world!"))
</script>
Output: world,null,null,world!

Example 2
<script type= "Text/javascript" >
var str= "1 plus 2 equal 3"
document.write (Str.match (//d+/g))
</script>
Output: 1,2,3

11.replace ()
Definitions and usage
The replace () method replaces some characters in a string with some other characters, or replaces a substring that matches a regular expression.

Grammar
Stringobject.replace (regexp,replacement)
Parameter description: RegExp required. The RegExp object that sets the pattern to be replaced. Note that if the value is a string, it is used as the direct text pattern to retrieve, not first converted to the RegExp object.
Replacement required. A string value. Provides a function that replaces text or generates alternate text.
return value
A new string that is replaced with replacement for the first match of RegExp or after all matches have been made.

Description
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 no match will be replaced by the string. However, the $ character in replacement has a specific meaning. As shown in the following table, it shows that the string that is matched from the pattern will be used for substitution.

Character replacement text
$ 、...、 $99 The text that matches the 1th to 99th subexpression in the RegExp.
$& the substring that matches the regexp.
$ ' is the text on the left side of the matching substring.
$ ' is the text on the right side of the matching substring.
$$ Direct measure symbol.

Note: The ECMAScript v3 stipulates that the parameter replacement of the replace () method can be a function rather than a string. In this 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.

Example 1
<script type= "Text/javascript" >
var str= "Visit microsoft!"
document.write (Str.replace (/microsoft/, "W3school"))
</script>
Output: Visit w3school!

Example 2: Global Search
<script type= "Text/javascript" >
var str= "Welcome to microsoft! "
Str=str + "We are proud to announce" Microsoft has "
Str=str + "One of the" largest WEB developers sites in the world. "

document.write (Str.replace (/microsoft/g, "W3school"))
</script>
Output:
Welcome to w3school! We are proud to announce that W3school
has one of the largest WEB developers sites in the world.

Example 3: An insensitive search for case sensitivity
Text = "JavaScript Tutorial";
Text.replace (/javascript/i, "JavaScript");

Example 4: How to use Replace () to convert the format of names.
Name = "Doe, John";
Name.replace (/(/w+)/s*,/s* (/w+)/, "$ $");

Example 5: How to use Replace () to convert quotation marks.
Name = ' "A", "B";
Name.replace ([^ "]*)"/g, "' $ '");

Example 6: How to use Replace () to convert the first letter of a word to uppercase.
Name = ' AAA bbb CCC ';
Uw=name.replace (//b/w+/b/g, function (word) {
Return word.substring (0,1). toUpperCase () +word.substring (1);}
);

12.search ()
Definitions and usage
The search () method retrieves the substring specified in the string, or retrieves a substring that matches the regular expression.

Grammar
Stringobject.search (regexp) parameter description
RegExp This parameter can be a substring that needs to be retrieved in Stringobject, or it can be a RegExp object that needs to be retrieved.

Note: To perform a retrieval that ignores case, append flag I.

return value
The starting position of the first substring in the stringobject that matches the regexp.

Note: If no matching substring is found, return-1.

Description
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.

Example 1
<script type= "Text/javascript" >
var str= "Visit w3school!"
document.write (Str.search (/w3school/))
</script>
Output: 6

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

Grammar
Stringobject.slice (start,end) parameter description
The starting subscript of the fragment to be extracted by start. 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.
End is immediately followed by the bottom 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.

return value
A new string. Includes all characters for the string stringobject from start (including start) to end ending (excluding ends).

Description
The string object's methods slice (), substring (), and substr () (not recommended) can return the specified portion of the character strings. Slice () is more flexible than substring () because it allows negative numbers to be used as parameters. Slice () differs from substr () because it specifies a substring with a two-character position, while substr () specifies the substring by character position and length.

Also note that String.slice () is similar to Array.slice ().

Example 1
<script type= "Text/javascript" >
var str= "Hello Happy world!"
document.write (Str.slice (6))
</script>
Output: Happy world!

Example 2
<script type= "Text/javascript" >
var str= "Hello Happy world!"
document.write (Str.slice (6,11))
</script>
Output: Happy

14.split ()
Definitions and usage
The split () method is used to split a string into an array of strings.

Grammar
Stringobject.split (separator,howmany) parameter description
Separator required. A string or regular expression that splits the Stringobject from the place specified by the parameter.
Howmany Optional. This parameter specifies the maximum length of the array to return. If this argument is set, the returned substring will not be more than the array specified by this parameter. If this argument is not set, the entire string is split, regardless of its length.

return value
An array of strings. The array is created by splitting the string stringobject into substrings at the boundary specified by separator. The string in the returned array does not include the separator itself.

However, if separator is a regular expression that contains a subexpression, the returned array includes a string that matches the subexpression (but does not include text that matches the entire regular expression).
Tips and comments
Note: If an empty string ("") is used as a separator, then each character in the Stringobject is split.

Note: The actions performed by String.Split () are the opposite of those performed by Array.join.

Example 1
<script type= "Text/javascript" >
var str= "How are your doing today?"

document.write (Str.split ("") + "<br/>")
document.write (Str.split ("") + "<br/>")
document.write (Str.split ("", 3))
</script>
Output:
How,are,you,doing,today?
H,o,w, A,r,e, Y,o,u, D,o,i,n,g, T,o,d,a,y,?
How,are,you

Example 2
"2:3:4:5". Split (":")//will return ["2", "3", "4", "5"]
"|a|b|c". Split ("|")//will return ["", "a", "B", "C"]

Example 3: If you need to return only a subset of the characters, use the Howmany parameter:
"Hello". Split ("", 3)//May return ["H", "E", "L"]

15.substr ()
Definitions and usage
The substr () method extracts a specified number of characters from the start subscript in a string.

Grammar
STRINGOBJECT.SUBSTR (start,length) parameter description
Start Required. The starting subscript of the substring to extract. Must be a numeric value. If it is a negative number, the argument declares the position from the tail of the string. In other words,-1 refers to the last character in the string, 2 to the penultimate character, and so on.
Length is optional. The number of characters in the substring. Must be a numeric value. If this argument is omitted, the string from the start position of the stringobject to the end is returned.

return value
A new string that contains the lenght character starting at the start of the Stringobject, including the character that the start refers to. If lenght is not specified, the returned string contains characters from the end of start to Stringobject.
Tips and comments
Note: the substr () parameter specifies the start position and length of the substring, so it can be used instead of substring () and splice ().

Important: ECMAscript does not standardize the method and is therefore opposed to its use.
Important: In IE 4, the value of the parameter start is invalid. In this BUG, start sets the position of the No. 0 character. In later versions, this BUG has been fixed.

Example 1
<script type= "Text/javascript" >
var str= "Hello world!"
document.write (STR.SUBSTR (3))
</script>

16.substring ()
Definitions and usage
The substring () method extracts characters from a string mediation between two specified subscripts.

Grammar
Stringobject.substring (start,stop) parameter description
Start Required. A non-negative integer that sets the position of the substring to be extracted at the first character in the Stringobject.
Stop is optional. A non-negative integer that is 1 more than the last character of the substring to extract in the Stringobject. If this argument is omitted, the returned substring continues to the end of the string.

return value
A new string that contains a substring of stringobject whose contents are all characters from the start to the stop-1, whose length is stop minus start.

Description
The substring returned by the substring () method includes the character at start, but does not include the character at the end.

If the argument start is equal to end, then the method returns an empty string (that is, the length 0). If start is larger than end, the method swaps the two parameters before extracting the substring.
Tips and comments
Important: Unlike the slice () and substr () methods, substring () does not accept negative parameters.

Example 2
<script type= "Text/javascript" >
var str= "Hello world!"
document.write (str.substring (3,7))
</script>

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.