Javascript Regular Expressions (supported by Regexp objects, attributes, methods, and strings)

Source: Internet
Author: User

Javascript Regexp Object Reference Manual http://www.w3school.com.cn/js/jsref_obj_regexp.asp

 

Regexp object

Regexp Object Attributes

Regexp object Method

Methods for string objects that support regular expressions

 

 

Regexp object

The Regexp object represents a regular expression, which is a powerful tool for matching string execution modes.

Direct Syntax:/Pattern/attributes

Syntax for creating a Regexp object:New Regexp (pattern, attributes );

Parameters
The pattern parameter is a string that specifies the regular expression mode or other regular expressions.

The attributes parameter is an optional string that contains the attributes "g", "I", and "M". It is used to specify global matching, case-sensitive matching, and multi-row matching, respectively. Before ecmascript standardization, the M attribute is not supported. This parameter must be omitted if pattern is a regular expression rather than a string.

Return Value
A new Regexp object with the specified pattern and flag. If the pattern parameter is a regular expression rather than a string, the Regexp () constructor creates a new Regexp object with the same pattern and flag as the specified Regexp.

If Regexp () is called as a function instead of the new operator, it performs the same behavior as when it is called using the new operator. It only returns pattern when pattern is a regular expression, instead of creating a new Regexp object.

Throw
Syntaxerror-If pattern is not a valid regular expression, or attributes contains characters other than "g", "I", and "M", this exception is thrown.

Typeerror-If pattern is a Regexp object but the attributes parameter is not omitted, this exception is thrown.

 

Regexp Object Attributes

Whether the global Regexp object has a flag.

Whether the ignorecase Regexp object has flag I.

Lastindex is an integer that indicates the next matching character position.

Whether the multiline Regexp object has a flag M.

Source Text of the source regular expression.

 

Regexp object Method

Compile can also be used to compile regular expressions.

Exec retrieves the value specified in the string. Return the value found and locate it.

The Exec () method is very powerful. It is a common method, and it is more complicated to use than the test () method and the string object method that supports regular expressions.

1. repeatedly calling the exec () method in a loop is the only method to obtain the complete pattern matching information in the global mode.

 
<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school"; var patt = new Regexp ("w3school", "G"); var result; while (result = patt.exe C (STR ))! = NULL) {document. write (result); document. write ("<br/>"); document. write (result. lastindex) ;}</SCRIPT>/* output: w3school14 */

2. If exec () finds the matched text, an array of results is returned. Otherwise, null is returned.

The first element of this array is the text that matches the regular expression, and the second element is the first element of regexpobject.Subexpression (parentheses reference a part of a regular expression)For the matched text (if any), the 2nd elements are the text (if any) that matches the 2nd subexpression of regexpobject, and so on.

In addition to the array element and Length attribute, the exec () method returns two attributes. The index attribute declares the position that matches the first character of the text. The INPUT attribute stores the retrieved string.

VaR Re =/(DS) + (J + S)/ig; var STR = "cfdsjs * (& dsjjjsyjsjs 888 dsdsjs"; var resultarray = re.exe C (STR ); while (resultarray) {document. writeln (resultarray [0]); document. writeln ("next match starts at" + RE. lastindex + "<br/>"); For (VAR I = 1; I <resultarray. length; I ++) {document. writeln ("substring of" + resultarray [I] + "<br/>");} document. writeln ("<br/>") resultarray = re.exe C (STR);}/* output: dsjs next match starts at 6 substring of dssubstring of jsdsjjjs next match starts at 16 substring of dssubstring of jjjsdsdsjs next match starts at 31 substring of dssubstring of js */

Test retrieves the value specified in the string. Returns true if it contains the specified value; otherwise, returns false.

Call the test () method of Regexp object R and pass the string s for it. It is equivalent to this representation: (r.exe C (s )! = NULL ).

<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school"; var patt1 = new Regexp ("w3school"); var result = patt1.test (STR); document. write ("Result:" + result); </SCRIPT>/* output: Result: true */

 

Methods for string objects that support regular expressions

Search retrieves the value that matches the regular expression.

If no matched substring is found,-1 is returned.

To perform a case-insensitive search, append flag I.

The search () method does not perform global match. It ignores the flag. 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.

<SCRIPT type = "text/JavaScript"> var STR = "Visit w3school! "Document. Write (Str. Search (/w3school/I) </SCRIPT>/* output: 6 */

Match finds matching of 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.

In global mode, we recommend that you use regexp.exe C () instead of this method.

Replace replaces the substring that matches the regular expression.

Stringobject. Replace (Regexp/substr,Replacement)

The Replace () method of the string stringobject performs the search and replace operation. It will search for the Child string that matches Regexp in stringobject, and then useReplacementTo replace these substrings.If Regexp has a global flag, the Replace () method replaces all matched substrings.Otherwise, it only replaces the first matched substring.

ReplacementIt 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 in the following table, it indicates that the string obtained from pattern matching will be used for replacement.

Character Replace text
$1, $2,..., $99 Text that matches the 1st to 99th subexpressions in Regexp.
$ & The substring that matches the Regexp.
$' Text on the left of the matched substring.
$' Text on the right of the matched substring.
$ Directly count the symbols.

Note:Ecmascript V3 stipulates that the replacement parameter of the Replace () method can be a function rather than a string. In this case, each match calls 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.

// 1. Perform a global replacement. When "Microsoft" is found, it is replaced with "w3school ": <SCRIPT type = "text/JavaScript"> var STR = "Welcome to Microsoft! "Str = STR +" We are proud to announce that 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 w3schoolhas one of the largest Web developers sites in the world. example 3 * // 2. Make sure that the uppercase characters of the matched string are correct: text = "javascript tutorial"; text. replace (/JavaScript/I, "JavaScript"); // 3. Convert "doe, John" to "John Doe" in the form of name = "doe, John "; name. replace (/(\ W +) \ s *, \ s * (\ W +)/, "$2 $1 "); // 4. Replace all quotation marks with straight quotation marks: Name = '"A", "B"'; Name. replace (/"([^"] *) "/g," '$ 1' "); // 5. Convert the first letter of all words in the string to uppercase: name = 'aaa bbb ccc '; UW = Name. replace (/\ B \ W + \ B/g, function (Word) {return word. substring (0, 1 ). touppercase () + word. substring (1 );});

Split splits the string into a string array.

Stringobject. Split (Separator,Howmany)

Howmany: Optional. This parameter specifies the maximum length of the returned array. If this parameter is set, no more substrings are returned than the array specified by this parameter.

Note: If the empty string ("") is usedSeparator, Each character in the stringobject will be split.

Note: The operations executed by string. Split () are the opposite to those executed by array. Join.

 

 

RecommendationArticle:

Msdn JScript 8.0 Regular Expression introduction http://msdn.microsoft.com/zh-cn/library/28hw3sce

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.