Replace and Replace regular expressions
Replace: replace the original character with a new character.
1. replace string replacement
var str = 'pku2016pku2017';str = str.replace('pku', 'pkusoft');console.log(str); // pkusoft2016pku2017
If the regular expression is not used, only one character can be replaced for each execution. Each execution starts from 0 and is duplicated.
2. replace regular expression replacement
Str = str. replace (/pku/g, 'pkusoft '); // use the regular global match console. log (str); // pkusoftsoft2016pkusoft2017
First, like exec capture, capture all matching regular expressions, and then replace the captured content with the new content we need to replace.
/Pku/g capture all matching items in str according to this regular expression, and then replace them with 'pkusoft'
If the second parameter of replace is a function
1. How many times the anonymous function is executed depends on how many times the regular expression can be captured in the string
2. Each time an anonymous function is executed, the arguments value is similar to the content captured through exec.
3. the return value is the content to be replaced.
Str = str. replace (/pku/g, function () {console. log (arguments); // the first execution: ["pku", 0, "pku2016pku2017"] // the first execution: ["pku", 7, "pku2016pku2017"] // The returned array is the same as the result returned by exec. return 'pkusoft ';}); console. log (str); // pkusoft2016pkusoft2017
Group capture of replace
Str = str. replace (/(\ d +)/g, function () {// console. log (arguments); // the first execution: ["2016", "2016", 7, "pkusoft2016pkusoft2017"] // the first execution: ["2017", "2017 ", 18, "pkusoft2016pkusoft2017"] // The returned array is the same as the result returned by exec. return '20170101';}); console. log (str); // pkusoft1_pkusoft0000
Replace applications
Var str = '000000'; var arr = ["zero", "one", "two", "three", "Si", "Wu", "Lu ", "comment", "comment", "comment"]; str = str. replace (/\ d/g, function () {var num = arguments [0]; // use the captured content as the subscript return arr [num];}); console. log (str); // returns zero, zero
Summary
The above is the regular expression in Replace introduced by the small editor. I hope it will be helpful to you. If you have any questions, please leave a message and the small editor will reply to you in time. Thank you very much for your support for the help House website!