如何在 JavaScript 中将一个字符串替换为另一个字符串?

M.R*_*yan 1 html javascript

考虑以下代码:

    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;
Run Code Online (Sandbox Code Playgroud)
<p id="demo"></p>
Run Code Online (Sandbox Code Playgroud)

字符串result与 相同text。我该如何解决这个问题?我只想将ain文本字符串中的每个内容替换为___.

Muh*_*lal 6

尝试这个

<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>
Run Code Online (Sandbox Code Playgroud)