0

我有这个脚本JsFiddle并且我正在尝试更改提交的字符,但是当您按下 for ex:s两次ss而不是显示xx它时将其更改为ss

完整代码:

<body>
    <div id='out'></div>

    <textarea id="in" name="messages" onkeyup="test()"></textarea>
    <input type="submit" id="submit" name="submit" />

js函数:

    function test(){            
        var origin = document.getElementById("in").value;
        var send = document.getElementById("out"); 

       if(origin =='s'){
        origin = 'z';
       }
        send.innerHTML = origin;
    }

    </script>
4

2 回答 2

1
var replacements = {
    "s": "z",
    // repeat for all the characters you want to replace
};

var neworigin = '';
for (var i = 0; i < origin.length; i++) {
    neworigin += (origin[i] in replacements) ? replacements[origin[i]] : origin[i];
    }
}
send.innerHTML = neworigin;
于 2013-05-12T19:16:06.547 回答
0

看起来您想在分配给之前替换所有s字符。您当前的代码仅替换为if is exactly one 。试试这个:zsendszorigins

send.innerTHML = origin.replace(/s/g, 'z');

这将替换每次出现的swith zinorigin并将结果分配给send.innerHTML. (如果它不明显,你可以摆脱这个if声明。)

如果您想用相同的替换字符替换所有字符,您可以将正则表达式从 更改/s/g/./g。如果要将每个字符替换为取决于字符的其他内容,可以使用查找功能:

var mapper = function(match) {
    return match === 's' ? 'z' : '?'; // or whatever mapping function you want
}
send.innerHTML = origin.replace(/./g, mapper);
于 2013-05-12T18:53:54.483 回答