Using Replace in JavaScript

Source: Internet
Author: User

The use of Replace in JavaScript is very powerful, not only can be replaced with a string, but also using regular expressions, the matching string to do whatever you want to do, first of all, let's look at the basic syntax of replace

Definition and usage

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

Grammar
Stringobject.replace (regexp/substr,replacement)

return value

A new string that is obtained after the first match or all matches of regexp have been replaced with replacement .

Description

The replace () method of the string Stringobject performs a find-and-replace operation. It looks for substrings in Stringobject that match regexp, and then replaces them with replacement .

If RegExp has global flag G, then the Replace () method replaces all matching substrings. Otherwise, it replaces only the first matched substring.

In order to get a deeper understanding of replace, we first practice the following demo;

var stringobj= "People's Republic of China, I am Chinese"; var str=stringobj.replace ("China", "United States"); Console.log (str);

The result of the output is: The People's Republic of America, I am Chinese

Only replaced the first China, if there are more than one China, it will need to replace each, very troublesome, this time can be replaced with regular expressions, then we can use regular expressions:

var stringobj= "People's Republic of China, I am Chinese"; var reg=New RegExp ("China", "G"); var str=stringobj.replace (Reg, "United States"); Console.log (str);

The result of the output is: The People's Republic of America, I am an American

G in RegExp represents the global flag, then the Replace () method replaces all matching substrings, otherwise it replaces only the first matched string.

If this is written in the example above: Var reg=new RegExp ("China"); will only replace the first one in China.

In the Replace function, we often encounter $1,$2,$3 ... This symbol, maybe we're not quite familiar with this, it represents the first, the second, the third in the RegExp. Text that matches the expression

var stringobj= "People's Republic of China, hello Kazakhstan China"; var str=stringobj.replace (/(Zhonghua)/g, "<font color=red>$1</font>"); Console.log (str); // The above code can also be written like this: var stringobj= "People's Republic of China, hello Kazakhstan China"; var reg=New RegExp ("(China)", "G"); var str=stringobj.replace (Reg, "<font color=red>$1</font>"); Console.log (str);

The result of the output is: <font color=red> China </font> People's Republic, hello Kazakhstan <font color=red> China </font>

$ $ represents the first sub-match, which is the second sub-match (the first parenthesis of the left expression, the second parenthesis)

For example: we convert "Alice,rock" to: "Rock,alice"

var stringobj= "Alice,rock"; var reg=New RegExp ("(\\w+) \s*,\s* (\\w+)"); var str=stringobj.replace (Reg, "$2,$1"); Console.log (str);

Output: Rock,alice

Can also be written as: Stringobj.replace (/(\w+) \s*, \s* (\w+)/, "$ $");

The second parameter of the Replace function, replacement , can be a string or a function, for example:

var strobject= "He is 28 years old, his daughter is 6 years old, his wife is 28 years old"; function Test ($) {   var year=New Date (). getFullYear ()-parseint ($);   Console.log ($1);    return $1+ "(" +year+ "Year of Birth)"}var reg=/(\d+) years/G; var str=strobject.replace (reg,test); Console.log (str);

The result of the output is:

28 years old

6 years old

28 years old

He is 28 years old (born in 1987) and his daughter is 6 years old (born in 2009) and his wife is 28 years old this year (born in 1987)

The output 3 times is because the match to three times, so the test executes three times, finally the matching characters to the operation, return the new string, so say can be matched to the character to do whatever.

There are two kinds of syntax for RegExp objects

Direct volume syntax
/pattern/attributes
Syntax for creating REGEXP objects:
New RegExp (patternattributes);

The attributes parameter has three types of values

I-case insensitive match

G performs a global match (finds all matches rather than finds the first match stop)

M performs multi-line matching

Contrast these two ways: object creation requires two escapes of quotation marks "and escape symbols" \ "such as:

var reg=/(\d+) years/G; // equivalent to: var reg=New RegExp ("(\\d+) years old", "G"); var reg=/(Zhonghua)/ /// equivalent to:var reg=New RegExp ("China", "G");

Comprehensive exercises

Use Replace to remove <meta name= "Location" content= "province= Hainan; city= Sanya; coord=109.518466229644,18.2585830170558" > Contents of content in tags (not including double quotes)

var strobj= ' <meta name= "location" content= "province= Hainan; city= Sanya; coord= 109.518466229644,18.2585830170558 ">"; var str=strobj.replace (/(. *?\ ") (p.*?) (\ ". *)/," $ "); Console.log (str) ;

Output: province= Hainan; city= Sanya; coord=109.518466229644,18.2585830170558

Using Replace in JavaScript

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.