Home  >  Article  >  Web Front-end  >  How to use the javascript string replacement function to replace everything at once_javascript skills

How to use the javascript string replacement function to replace everything at once_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:34:162116browse

JS string replacement function: Replace(“String 1″, “String 2″)

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

<script> 
var s = "LOVE LIFE ! LOVE JAVA ..."; 
alert(s); 
alert(s.replace("LOVE ", "爱")); 
alert(s.replace(/\LOVE/g, "爱")); 
</script> 

Save the above code into an HTML file and you can see the effect in the browser.

How about it? If you understand, you don’t need to read further. If you don’t understand, just continue reading:

In fact, we used regular expressions in JS. /LOVE in /LOVE/g means to find a string. What we are looking for are quotation marks. /g is the syntax of regular expression, which means all the meaning. Here it means replace all.

So the meaning of the above code is to remove all the quotation marks in the string.

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

So let’s take a 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,"爱")); 
</script>[color=olive]

The above content is a tutorial on how to replace all JS string replacement functions at once. I hope you like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn