replace means replacement in English. There is also a replace function in programming, so how to use it? In this article, we will share with you the method of replace to replace the original characters with new characters, that is, in replace Regular replacement.
replace: Replace the original characters with new characters
1. Replace string replacement
var str = 'pku2016pku2017'; str = str.replace('pku', 'pkusoft'); console.log(str); // pkusoft2016pku2017
without using regular expressions Under, each execution can only replace one character. 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
First, just like exec capture, capture all the regular expressions that match us, 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
replace group capture
str = str.replace(/(\d+)/g, function () { // console.log(arguments); // 第一次执行: ["2016", "2016", 7, "pkusoft2016pkusoft2017"] // 第一次执行: ["2017", "2017", 18, "pkusoft2016pkusoft2017"] // 返回的数组和执行exec返回的结果一致 return '0000'; }); console.log(str); // pkusoft0000pkusoft0000
replace application
var str = '20171001'; var arr = ["零","壹","贰","叁","肆","伍","陆","柒","捌","玖"]; str = str.replace(/\d/g,function () { var num = arguments[0]; // 把捕获的内容,作为数组的下标 return arr[num]; }); console.log(str); // 贰零壹柒壹零零壹
The above content is Regular replacement tutorial of replace, I hope it can help everyone.
Related recommendations:
php Detailed explanation of string regular replacement function preg_replace
Share two regular replacement functions implemented in JS and C# Example
Detailed explanation of JS regular replacement method to remove spaces
The above is the detailed content of Regular replacement of replace. For more information, please follow other related articles on the PHP Chinese website!