Home > Web Front-end > JS Tutorial > Detailed explanation of replace function usage

Detailed explanation of replace function usage

php中世界最好的语言
Release: 2018-04-18 10:58:16
Original
4527 people have browsed it

This time I will bring you a detailed explanation of the use of the replace function. What are the precautions when using the replace function. The following is a practical case, let's take a look.

The syntax of the replace method is: stringObj.replace(rgExp, replaceText) where stringObj is a string( string), reExp can be a regular expression object (RegExp) or a string (string), replaceText is to replace the found string. .

Without further ado, I will post the code directly for you. The specific code is as follows:

 <script>
var str = "a1ba2b";
var reg = /a.b/g;
str = str.replace(reg,function(a,b){
 console.log(a);
 console.log(b);
 return b == 0 ? a.replace("a","0") : a.replace("b","3");
});
console.log(str);
/*
输出结果为:
a1b
0//第一次匹配到a1b,将a置为0.
a2b
3//第二次匹配到a2b,将b置为3.
01ba23//返回经过修改后的字符串
*/
/*
function(a,b,c)一共可以传入3个参数,第一个为匹配的字符串,第二个为匹配字符串的起始位置,
第三个为调用replace方法的字符串本身。可以缺省c或b、c。
*/
</script>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed installation steps of JSONBuddy

JS encapsulation plug-in case

Detailed explanation of using webpack2 React

The above is the detailed content of Detailed explanation of replace function usage. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template