JavaScript string replacement function How to replace all the _javascript tips

Source: Internet
Author: User

JS string substitution function: replace ("String 1″," string 2″)

1. We all know that the string substitution function in JS is replace ("String 1″," string 2″), but this function can only replace the first occurrence of the string 1, so how can we replace all at once?

<script> 
var s = "Love life!" Love JAVA ... "; 
alert (s); 
Alert ("Love", "S.replace"); 
Alert (S.replace (/\love/g, "Love")); 

You can see the effect in your browser by saving the above code to an HTML file.

What do you think? If you understand the need to look down, do not understand and then look down:

In fact, we use the regular expression in JS,/\love/g/\love is to find the string, which we are looking for is the quotation marks,/g is the regular expression of the syntax, to express all the meaning, here is to represent the replacement.

So the above code means to remove all the quotes in the string.

2. Now we know how to replace all the strings, but what if we were to pass love as a parameter to the regular expression?

So let's look at how the following piece of code is implemented:

<script> 
var s = "Love life!" Love JAVA ... "; 
alert (s); 
var tmp= "Love"; 
var reg=new RegExp (""); 
Alert (S.replace (Reg, "Love")); 
</script>[color=olive]

The above content is about JS string replacement function How to replace all the relevant tutorials, I hope you like.

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.