用户输入时替换字(JS) [英] Word replacement while user is typing input (JS)

查看:160
本文介绍了用户输入时替换字(JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a code that displays what an user is typing and that input is written down back into a in the html document.

这是下面的代码:

<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>

有人可以帮我找出如何使它替代一个单词或

Can someone please help me to figure out how I can make it so that it replaces a word or a line of string into something else live while the user is typing.

例如,用户写这是一个字符串...程序将其写在html文档,但也自动将特定字符串更改为这是一个文本从这是一个字符串..
请帮助!

For example is the user writes "this is a string" ... the program writes it down on the html document, but also automatically changes that specific string into something like "This is a text" from "This is a string".. Please help!

推荐答案

请参阅我的小提示这里

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

I created an object where you can add all the strings you need to replace in a key-value pair. Please keep in mind to escape special characters for RegExp though (with a \).

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);
});

这篇关于用户输入时替换字(JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆