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>