替换JavaScript中的单词

use*_*769 -3 html javascript string replace

我只想交换字符串中的单词,考虑:

var str = "this is a test string";
Run Code Online (Sandbox Code Playgroud)

现在测试应该用string替换,字符串应该被test替换,以便输出应该是

"this is a string test"
Run Code Online (Sandbox Code Playgroud)

实际代码:

<html>
<title> Swappping Words </title>
<body>
    <script type="text/javascript">
        var o_name = prompt("Enter the String", "");
        var replace1 = prompt("Enter the first word to replace ", "");
        var r1 = prompt("replacing word of 1", "")
        var replace2 = prompt("Enter the second word to replace ", "");
        var r2 = prompt("replacing word of 2", "")
        var n_name1 = o_name.replace(replace1, r1).replace(replace2, r2);
        document.writeln("Old string = " +o_name);
        document.writeln("New string = " +n_name1);
    </script>  
</body>
Run Code Online (Sandbox Code Playgroud)

我正在学习基础知识,有人可以向我解释如何做到这一点吗?

Nie*_*sol 9

您将面临的主要问题是,除非您同时进行两次更换,否则您将面临用第二次更换第一次替换的风险.

试试这个:

var result = str.replace(/test|string/g,function(m) {
    switch(m) {
        case "test": return "string";
        case "string": return "test";
    }
});
Run Code Online (Sandbox Code Playgroud)