我有一个代码,可以显示用户正在输入的内容,并且该输入被写回 html 文档中。
这是下面的代码:
<html><head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="jquery.zclip.js"></script>
<style> body{font-family:century gothic;}</style>
</head>
<body style="zoom: 1;">
<div style="padding:10%;">
<textarea type="text" name="fname" class="chatinput" style="margin: 0px; width: 977px; height: 324px;"> </textarea>
<div style="padding-top:10%;" class="printchatbox"></div>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script src="jquery.zclip.js"></script>
<script type="text/javascript">
$('.chatinput').keyup(function(event) {
newText = event.target.value;
$('.printchatbox').text(newText);
});
</script>
有人可以帮我弄清楚如何制作它,以便在用户打字时将一个单词或一行字符串替换为其他内容。
例如,用户写“这是一个字符串”...程序将其写在 html 文档上,但也会自动将该特定字符串从“这是一个字符串”更改为“这是一个文本” “.. 请帮忙!
最佳答案
请看我的 fiddle here .
我创建了一个对象,您可以在其中添加需要在键值对中替换的所有字符串。请记住,要转义 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);
});
关于javascript - 用户输入时进行单词替换 (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31834054/