JS Replace the default substitution replaces only the first matching character, if the string has more than two characters can not be replaced, it is necessary to do a little operation, to replace all.
<script language= "JavaScript" >var strM = "This is the string to be replaced AH Ah!" "; // Here I want to replace the letter A with the letter aalert (strm.replace ("Ah", "sum")); </script>
The above code, can only replace the first character "Ah", the second "ah" can not be replaced, so there is no way to meet the majority of the use of JS (replace) requirements
<script type= "Text/javascript" language= "JavaScript" >var s = "This is the character to be replaced!" alert (s), alert (S.replace (/AH/g, "sum"));
In this way, the entire string substitution can be achieved.
Here we use the/g of the regular function. This enables the substitution of the entire string.
Below, we all may have a demand is not satisfied, that is, we can replace the fixed value to use this, but how to use the replacement variable?
Next, let's talk about how the substitution variables are used.
A brief introduction to the eval () function computes a string and executes the JavaScript code in it. The next step is to rely on this function.
<script>var ch = "variable"; var reg = "/" +ch+ "/g"; var str = "This is a variable, this is a variable"; var val = str.replace (eval (reg), "replace"); alert (val); </script>
However, if you want to replace the string containing the/symbol, the above is not used, you need to take the following methods
<script>var ch = "/"; var str = "This is a variable, this is a variable"; var val = str. replace (new RegExp (ch, ' G '), "B"), alert (val); </script>
JS Replace global Replace