Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 15:34:16
Original
2136 people have browsed it

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> 
Copy after login

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]
Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template