用户输入输入(JS)时替换单词

我有一个代码,显示用户正在键入的内容,并将该输入写回html文档中的a。

这是下面的代码:

    body{font-family:century gothic;}   
$('.chatinput').keyup(function(event) { newText = event.target.value; $('.printchatbox').text(newText); });

有人可以帮我弄清楚我是如何做到这一点的,以便在用户输入时将一个字或一行字符串替换成其他的字符串。

例如,用户写“这是一个字符串”…程序将其写在html文档上,但也会自动将该特定字符串更改为“This is a text”中的“This is a string”。请帮忙!

请在这里看看我的小提琴。

我创建了一个对象,您可以在键对中添加需要替换的所有字符串。 请记住,要转义RegExp的特殊字符(使用\ )。

JS

 var replaceValues = { 'string' : 'text', 'foo' : 'bar' } $('.chatinput').keyup(function (event) { newText = event.target.value; for (var txt in replaceValues) { var temp = new RegExp(txt, 'gim'); newText = newText.replace(temp, replaceValues[txt]); } $('.printchatbox').text(newText); }); 

您可以在变量上使用replace函数。