Consider the following code:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var text2='ain';
let text = "The rain in SPAIN stays mainly in the plain";
let result = text.replaceAll(/text2/g,'__');
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
The string result
is the same as text
. How do I fix this problem? I just want every ain
in text string to get replaced with ___
.
3
Answers
Try this
Need to create a new regular expression using the RegExp constructor and pass the text2 variable and the ‘g’ flag to make the replacement global, you can use the following code:
If you want to replace the ‘AIN’ in capital letters too. That can be done by adding the ‘i’ flag to the regular expression, then it becomes case-insensitive.