js replace Global replacement [turn]

The default replacement of js replaces only the first matching character. If there are more than two corresponding characters in the string, it cannot be replaced. At this time, a little operation is required to perform all replacements.

var str = "javascript";
console.log(str .replace("a","A"));//输出:jAvascript

The above code can only replace the first character "ah", the second "a" cannot be replaced, so there is no way to meet most of the needs of using js (replace)

var str = "javascript";
console.log(str.replace(/a/g, "A"));//输出:jAvAscript

In this way, the entire string can be replaced.
We used all of the regular function / g here. This can achieve the replacement effect of the entire string.
Below, we may still have a need that cannot be met, that is, we can use this instead of the fixed value, but how to use the replacement variable?
Next, let's talk about the use of substitution variables.
Briefly introduce the eval()function can calculate a certain string and execute the JavaScript code in it. Next, mainly rely on this function.

var ch = "a";
var reg = "/"+ch+"/g";
var str = "javascript";
console.log( str.replace(eval(reg),"A"));//输出:jAvAscript

However, if the string to be replaced contains /symbols, the above cannot be used, and the following methods need to be adopted

var ch = "/";
var str = "java/script";
console.log(str .replace(new RegExp(ch,'g')," "));//输出:java script

Article reference: https://www.cnblogs.com/stubborn-donkey/p/9173089.html

Guess you like

Origin www.cnblogs.com/KillBugMe/p/12693180.html