Use of JavaScript (replace all, variable substitution) __java

Source: Internet
Author: User

JS Replace default replaces only the first matching character, if the string has more than two corresponding characters can not be replaced, this time to do a little operation, complete replacement.

[HTML] View plain copy <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 a alert (Strm.replace ("Ah", "amount")); </script> above the 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.

[HTML] View plain copy <script type= "Text/javascript" language= "JavaScript" > var s = "This is to be replaced by the character change Ah ah."   ";   alert (s); Alert (s.replace (/AH/g, "amount"));
This enables the replacement of the entire string.

We use the/g of regular functions here. This allows you to implement the entire string substitution effect.

Below, we may all have a need to be unable to meet, that is, we replace the fixed value can use this, but the replacement variable how to use.

Next, let's say how the substitution variable is used.

A brief introduction to the eval () function computes a string and executes the JavaScript code in it. This is the main function next.

[HTML] View plain copy <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>
This satisfies the way the variable is replaced.


Turn from: http://blog.csdn.net/z714359830/article/details/51564878
Top 0 Step 0

Related Article

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.