输入 JavaScript 后修改字符或单词

发布于 2024-12-12 00:39:39 字数 329 浏览 0 评论 0 原文

假设我正在文本区域中输入“hello”一词。在我输入 hello 后,我如何选择我刚刚输入的单词并修改它。例如,在我输入“hello”一词后,无需按空格键,就识别出该词是“hello”,并在其前后添加 周围的单词。所以最终结果将是 hello 我知道 textarea 不接受 HTML,但为了论证。我能想到的唯一方法是每次用户按下一个键时运行一个函数,并将文本区域的内容添加到一个数组中,在空格处打破它。但这需要空格,并且交叉引用数组会花费时间。有办法轻松做到这一点吗?

Lets say I am typing the word "hello" into a textarea. How would I, after I had typed hello, select that word I had just typed, and modify it. For example, after I typed the word hello, without hitting the space bar, recognize the word is hello, and before and after it add <b> and </b> around the word. So the ending result would be <b>hello</b> I know textarea's don't take HTML, but for the sake of argument. The only way I can think to do this is to run a function each time the user presses a key, and add the content of the textarea to an array, breaking it at the spaces. But that requires spaces, and than having to cross reference the array will take time. Is there anyway to do this easily?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

可爱暴击 2024-12-19 00:39:39

如果您希望它在您键入时进行替换,那么您肯定必须捕获每个按键,但您不必测试空格。当我在 IE 中测试它时,以下内容有效:

$(function() {
   $("#yourtextareaidhere").keyup(function(e) {
      var updatedText = this.value.replace(
                               /(^|[^>])(hello)($|[^<])/gi, "$1<b>$2</b>$3");
      if (updatedText != this.value)
         this.value = updatedText;
   });
});

基本上在每次按键时都会进行字符串替换,以获取尚未被“>”包围的“hello”的所有实例。和“<” (包括“hello”位于字符串开头或结尾的位置),并替换为 hello。如果字符串替换的结果与字段中的结果不同(即,确实发生了某些替换),则新值将写回文本区域 - 我不只是每次都直接写回,因为这会丢失光标这对用户来说很烦人,我懒得想出比这个简单的“if”测试更好的解决方法。 (我之所以这样做是因为我为您提供了一个“起始位置”,然后将其余的留给您。)

这种方法考虑到了这样一个事实:用户可能不会一次性输入“hello”一词,例如,如果他们打错了字,最初是“我对你说你好”,然后返回并添加了“e”,那么你(大概)想要替换“你好”,即使它不在最后。我还进行了全局替换,这样如果用户粘贴“hello hello hello”,它们都会被替换。自行决定是否需要不区分大小写的替换。

如果您还想替换其他单词,则可以将它们添加到相同的正则表达式中(如果它们都只需要粗体标签),否则如果每个特殊单词都有自己所需的格式,则定义搜索正则表达式和替换字符串的数组并循环在函数内通过它们。

请注意,我的正则表达式有点生疏,所以如果有更好的方法来做同样的事情,我一点也不会感到惊讶,但我会将任何改进作为练习留给读者。

You'll definitely have to trap each keypress if you want it to do the replacement as you type, but you don't have to test for spaces. The following worked when I tested it in IE:

$(function() {
   $("#yourtextareaidhere").keyup(function(e) {
      var updatedText = this.value.replace(
                               /(^|[^>])(hello)($|[^<])/gi, "$1<b>$2</b>$3");
      if (updatedText != this.value)
         this.value = updatedText;
   });
});

Essentially on every keypress this does a string replace to take all instances of "hello" not already surrounded by ">" and "<" (including where "hello" is at the start or end of the string), and substitute in "<b>hello</b>". If the result of the string replace is different to what was in the field (i.e., some substitution did occur) then the new value is written back to the textarea - I don't just write it back directly every time because that loses the cursor position which is annoying for the user and I'm too lazy to come up with a better workaround than this simple "if" test. (I justify this on the basis that I'm providing you with a "starting place", and leaving the rest to you.)

This approach allows for the fact that the user may not have typed the word "hello" in one go, e.g., if they made a typo and initially had "I say hllo to you" then went back and added the "e" then you (presumably) want to replace the "hello" even though it isn't at the end. Also I do a global replace so that if the user pastes in "hello hello hello" they'll all be replaced. Decide for yourself if you want a case-insensitive replacement.

If there are other words you are looking to replace too you could add them to the same regular expression if they all just need the bold tags, otherwise if each special word has its own required formatting define an array of search regexes and replacement strings and loop through them within the function.

Note that my regular expressions are a bit rusty so I won't be at all surprised if there's a nicer way to do the same thing, but I'll leave any improvements as an exercise for the reader.

九八野马 2024-12-19 00:39:39

您可以使用 JQuery.keyup 函数来监听空格键按下。

$("textarea").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWhiteSpace = c.match(/\s/);
});

您可以使用分割join 函数也可以完成您在问题后半部分所描述的内容。

编辑:这里有更多关于这个想法的信息: http://jsfiddle.net/ingenu8/ukkwM/

<div class="formatted"></div>
<textarea class="observed"></textarea>

和JS:

$(document).ready(function() {
    function hasHtml(str)
    {
        return str.match(/<b>.*?<\/b>/);
    }

    function formatStr(str)
    {
        var bits = str.split(/\s+/);
        var last = bits.pop();
        if(!last.match(/^\s*$/))
        {
            if(!hasHtml(last))
            {
                bits.push('<b>'+last+'</b>');
            }
        }
        return bits.join(' ');
    }

    setInterval(function() {
        var str = formatStr($('.observed').val());
        $('.formatted').html(str);
    }, 1000);
});

You can use the JQuery.keyup function to listen for the space key press.

$("textarea").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWhiteSpace = c.match(/\s/);
});

You can use the split and join function as well to accomplish what you describe in the latter part of your question.

Edit: Here's more on this idea: http://jsfiddle.net/ingenu8/ukkwM/

<div class="formatted"></div>
<textarea class="observed"></textarea>

and the JS:

$(document).ready(function() {
    function hasHtml(str)
    {
        return str.match(/<b>.*?<\/b>/);
    }

    function formatStr(str)
    {
        var bits = str.split(/\s+/);
        var last = bits.pop();
        if(!last.match(/^\s*$/))
        {
            if(!hasHtml(last))
            {
                bits.push('<b>'+last+'</b>');
            }
        }
        return bits.join(' ');
    }

    setInterval(function() {
        var str = formatStr($('.observed').val());
        $('.formatted').html(str);
    }, 1000);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文