skip to Main Content

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


  1. Try this

    <script>
        const text2 = 'ain';
        const text = "The rain in SPAIN stays mainly in the plain";
    
        // Create a regular expression using the 'text2' variable as a string
        const regex = new RegExp(text2, 'g');
    
        // Use the 'regex' variable in the 'replaceAll' method
        const result = text.replaceAll(regex, '___');
    
        document.getElementById("demo").innerHTML = result;
    </script>
    
    Login or Signup to reply.
  2. let text2 = 'ain';
    let text = "The rain in SPAIN stays mainly in the plain";
    
    
    let replacedText2 = text2.replace(/ain/g, '--');
    
    console.log(replacedText2); 
    document.getElementById("demo").innerHTML = replacedText2;
    
    Login or Signup to reply.
  3. 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:

    <!DOCTYPE html>
    <html>
    
    <body>
        <p id="demo"></p>
    
        <script>
            const text2 = 'ain';
            const text = "The rain in SPAIN stays mainly in the plain";
            const regex = new RegExp(text2, 'g');
            const result = text.replaceAll(regex, '___');
    
            document.getElementById("demo").innerHTML = result;
        </script>
    
    </body>
    
    </html>

    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.

    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo"></p>
    
    <script>
        const text2 = 'ain';
        const text = "The rain in SPAIN stays mainly in the plain";
        const regex = new RegExp(text2, 'gi');
        const result = text.replaceAll(regex, '___');
     
        document.getElementById("demo").innerHTML = result;
    </script>
    
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search