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

Javascript 用户键入输入时替换单词(JS),javascript,jquery,css,arrays,html,Javascript,Jquery,Css,Arrays,Html,我有一个代码,显示用户键入的内容,并将输入写回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;}</styl

我有一个代码,显示用户键入的内容,并将输入写回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>

正文{字体系列:世纪哥特式;}
$('.chatinput').keyup(函数(事件){
newText=event.target.value;
$('.printchatbox').text(newText);
});  
有没有人能帮我弄清楚我该怎么做,以便在用户键入时,它能将一个单词或一行字符串替换为其他live内容

例如,用户写“这是一个字符串”。。。程序将其写在html文档中,但也会自动将特定字符串从“thisastring”更改为类似“thisatext”的内容。。 请帮忙


请看我的小提琴

我创建了一个对象,您可以在其中添加需要在键值对中替换的所有字符串。请记住转义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函数

<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.replace("This is a string","This is a text"));
});  
</script>

正文{字体系列:世纪哥特式;}
$('.chatinput').keyup(函数(事件){
newText=event.target.value;
$('.printchatbox').text(newText.replace(“这是字符串”,“这是文本”));
});  

目前我无法给出确切的代码响应,但有一种(有些不雅的)解决方案是将输入框转换为字符串,并在向上键时更新。然后,使用for循环迭代单词及其替换的关联数组。使用.indexOf方法查找输入字符串中的单词,然后拆分输入并从数组中提取所需的替换。是否有任何方法可以在textarea而不是HTML文档本身中打印替换值?请尝试以下方法:我将.printchatbox改为textarea而不是div。我还将JS更改为(.text to.val)我试过了,但由于某种原因,我做的时候它不起作用。但是,再次感谢您在Javascript中提供的帮助,是否有一种方法可以打断文本,使它们不会出现在彼此相邻的位置,而是出现在单独的行上我是JS的不速之客。对不起,你想在哪里休息?你能举个例子吗?