Rugleh Rugleh - 5 months ago 17
Javascript Question

match '+' in a string with str.match javascript

I was looking at this example:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp

<!DOCTYPE html>
<html>
<body>

<p>Click the button to perform a global search for the letters "ain+" in a string, and display the matches.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/ain+/g);
document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>


And it's what I need, but if I add a '+' at the end of 'ain' it does not work, how should I do it?

Answer Source

+ is a repetition character which means 1 or more. If you want to literally search for + then you need to escape it like this:

str.match(/ain\+/g)

<!DOCTYPE html>
<html>
<body>

<p>Click the button to perfom a global search for the letters "ain+" in a string, and display the matches.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var str = "The rain+ in SPAIN stays mainly in the plain"; 
    var res = str.match(/ain\+/g);
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>