JS Replace global Replace

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.