Home >Web Front-end >JS Tutorial >Introduction to advanced usage of JS Replace()_javascript skills

Introduction to advanced usage of JS Replace()_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:30:561074browse

In many projects, we often need to use JS to modify certain elements in the foreground in front of the page. The replace() method of js is essential.

Students who often use "ABCABCabc".replace("A","B") should know better. The final result of changing the statement is BBCABC. This method can only replace

The first matching element. What if you replace everything? Just use regular expressions:

"ABCABCabc".replace(/A/g,"B") will do.
What if you want to replace A and also replace a?

Then you can use "ABCABCabc".replace(/a/ig,"B");

Flag: i indicates ignore to ignore the size, g indicates global for repeated retrieval, and m indicates multi-line retrieval (this has not been tested yet)

You can also use a combination of them. For example, the ig used above replaces all identifiers and ignores case.

Formal regex writing:

Copy code The code is as follows:

var reg=new RegExp(/patten/flag)
var strs="".match(reg);

When flag uses g, strs returns a string array.

If you want to match any one of multiple strings, you can use

Copy the code The code is as follows:

reg=new RegExp(/abc|xyz/ig);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn