JS replace method_javascript tips-js tutorial

Source: Internet
Author: User
In javascript, the String function replace () is quite popular. It provides flexible and powerful character replacement processing capabilities. Here is a brief introduction to help you easily define and use it.
The replace () method is used to replace other characters with some characters in a string, or replace a substring that matches a regular expression.

Syntax
StringObject. replace (regexp/substr, replacement)

Parameters Description
Regexp/substr

Required. Specifies the substring or RegExp object of the pattern to be replaced.

Note that 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.

Replacement Required. A string value. Specifies the function for replacing text or generating replacement text.

Return Value

A new string is usedReplacementIt is obtained after the first match of regexp or all matches.

Description

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.

More basic instances can be viewed here: http://www.jb51.net/w3school/js/jsref_replace.htm

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.

The following describes several repalce methods with javascript Regular Expressions. Some methods are rarely seen elsewhere, such as the second and third-party methods.

The Code is as follows:


// The following example is used to obtain two url parameters and return the real Url before urlRewrite.
Var reg = new RegExp ("(http://www.qidian.com/BookReader/) (\ d +), (\ d +). aspx", "gmi ");
Var url = "http://www.qidian.com/BookReader/1017141,20361055.aspx ";

// Method 1: the simplest and most common method
Var rep = url. replace (reg, "$ 1ShowBook. aspx? BookId = $2 & chapterId = $3 ");
Alert (rep );

// Method 2: Use a callback function with fixed parameters
Var rep2 = url. replace (reg, function (m, p1, p2, p3) {return p1 + "ShowBook. aspx? BookId = "+ p3 +" & chapterId = "+ p3 });
Alert (rep2 );

// Method 3: callback function with non-fixed parameters
Var rep3 = url. replace (reg, function () {var args = arguments; return args [1] + "ShowBook. aspx? BookId = "+ args [2] +" & chapterId = "+ args [3];});
Alert (rep3 );


// Method 4
// Method 4 is similar to method 3. Besides returning the replaced string, you can also obtain parameters separately.

[Code]
Var bookId;
Var chapterId;
Function capText ()
{
Var args = arguments;
BookId = args [2];
ChapterId = args [3];
Return args [1] + "ShowBook. aspx? BookId = "+ args [2] +" & chapterId = "+ args [3];
}

Var rep4 = url. replace (reg, capText );
Alert (rep4 );
Alert (bookId );
Alert (chapterId );


// In addition to using the replace method to obtain the regular expression grouping, you can also use the test and exec methods to obtain the grouping, but the method is different.
Var reg2 = new RegExp ("(http://www.qidian.com/BookReader/) (\ d +), (\ d +). aspx", "gmi ");
Var m=reg2.exe c ("http://www.qidian.com/BookReader/1017141,20361055.aspx ");
Var s = "";
// Obtain all Groups
For (I = 0; I <m. length; I ++ ){
S = s + m [I] + "\ n ";
}
Alert (s );

BookId = m [2];
ChapterId = m [3];
Alert (bookId );
Alert (chapterId );


// Use the test method to obtain the group
Var reg3 = new RegExp ("(http://www.qidian.com/BookReader/) (\ d +), (\ d +). aspx", "gmi ");
Reg3.test ("http://www.qidian.com/BookReader/1017141,20361055.aspx ");
// Obtain three groups
Alert (RegExp. $1 );
Alert (RegExp. $2 );
Alert (RegExp. $3 );

Var str = "www.baidu.com ";
// Str. format ("good", "q ")
Str. replace (new RegExp ("(\.) (bai) du", "g"), function (){
For (var I = 0; I {
Document. write (arguments [I] +"
");
}
Document. write ("-------------------------------------------------
");
});

Two examples (proving that the results of the replace input regular parameters and the character passing parameters are different ):

Alert ("123". replace ("1", function () {var un; return un;}); // The undefined23 is displayed.
Alert ("123". replace (new RegExp ("1"), function () {var un; return un;}); // pop up 23

Some examples:


Replace () is a simple replacement of characters. For example:

<Script language = "javascript"> var strM = "javascript is a good script language"; // here I want to replace letter a with the letter A alert (strM. replace ("a", "A"); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]



I think you can see the result after running it. It only replaces the first letter. However, if you add a regular expression, the results will be different! Replace () supports regular expressions. It can match characters or strings according to the regular expression rules and then replace them!

<Script language = "javascript"> var strM = "javascript is a good script language"; // here I want to replace letter a with the letter A alert (strM. replace (/a/, "A"); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]



However, the results are still not changed. If you are familiar with regular expressions, this will be difficult for you. It will be OK after a slight modification.

The Code is as follows:


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.