This article mainly introduces the relevant knowledge of regular expressions in Replace. The article introduces the method of replace to replace the original characters with new characters. Friends who need it can refer to it. I hope it can help everyone.
replace: Replace the original characters with new characters
1. String replacement of replace
var str = 'pku2016pku2017'; str = str.replace('pku', 'pkusoft'); console.log(str); // pkusoft2016pku2017
is not used In the case of regularity, only one character can be replaced at each execution. Each execution starts from 0. If there are duplicates, all cannot be replaced.
2. Regular replacement of replace
str = str.replace(/pku/g, 'pkusoft'); // 使用正则的全局匹配 console.log(str); // pkusoftsoft2016pkusoft2017
Firstly, just like exec capture, we capture everything that matches our regular rules, and then replace the captured content with the new content we need to replace.
/pku/gFollow this regular rule to capture all matching items in str, and then replace them all with 'pkusoft'
replace if the second parameter is a function
1. Anonymous function The number of times it is executed depends on how many times the regular expression can be captured in the string
2. Each time the anonymous function is executed, the arguments value is very similar to the content captured through exec
3. return The value is the content that needs to be replaced
str = str.replace(/pku/g, function () { console.log(arguments); // 第一次执行: ["pku", 0, "pku2016pku2017"] // 第一次执行: ["pku", 7, "pku2016pku2017"] // 返回的数组和执行exec返回的结果一致 return 'pkusoft'; }); console.log(str); // pkusoftsoft2016pkusoft2017
Group capture of replacement
str = str.replace(/(\d+)/g, function () { // console.log(arguments); // 第一次执行: ["2016", "2016", 7, "pkusoft2016pkusoft2017"] // 第一次执行: ["2017", "2017", 18, "pkusoft2016pkusoft2017"] // 返回的数组和执行exec返回的结果一致 return '0000'; }); console.log(str); // pkusoft0000pkusoft0000
Application of replacement
var str = '20171001'; var arr = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]; str = str.replace(/\d/g,function () { var num = arguments[0]; // 把捕获的内容,作为数组的下标 return arr[num]; }); console.log(str); // 贰零壹柒壹零零壹
Related recommendations:
Example introduction to regular expression form validation
Using regular expressions in JS Expression to find the length of the longest continuous substring
Use regular expressions to highlight characters
The above is the detailed content of Regular Expressions in Replace_Regular Expressions. For more information, please follow other related articles on the PHP Chinese website!