从文本框中删除多余的单词 [英] Remove excess words from a textbox

查看:105
本文介绍了从文本框中删除多余的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个几乎完成的脚本,但我无法弄清楚最后一点。该脚本旨在限制可以输入到文本区域中的单词的数量,并且如果它们超过了单词限制,则会删除这些额外的单词。我有超过最大标记为超额的字数。例如,如果你输入了102个单词,那么超额就是2.我如何从文本区域中删除这两个单词?

I have a script which is almost complete but I can't figure out the last bit here. The script is meant to limit the amount of words that can be entered into a text area and if they go over the word limit these extra words are removed. I have the amount of words beyond the max labeled as overage. For instance, if you were to enter in 102 words, then the overage would be 2. How would I remove those two words from the text area?

jQuery(document).ready(function($) {
    var max = 100;
    $('#text').keyup(function(e) {
        if (e.which < 0x20) {
            return;
        }

        var value = $('#text').val();
        var regex = /\s+/gi;
        var wordCount = value.trim().replace(regex, ' ').split(' ').length;

        if (wordCount == max) {
            // Reached max, prevent additional.
            e.preventDefault();
        } else if (wordCount > max) {


            <!--Edited to show code from user3003216-->
            <!--Isn't working like this, textarea doesn't update.-->

            var overage = wordCount - max;
            var words = value.split(' ');
            for(var i = 0; i<overage; i++){
                words.pop();
            }

        }
    });         
});


推荐答案

最简单的方法就是计算在按键的字数,然后从那里开始。检查是否有更多的单词超过允许的数量。如果是这样,请删除所有多余的单词: while(text.length> maxWords)。然后,只需将文本框的值替换为更新的文本即可。

The easiest way to approach this is just to count the number of words on keypress and go from there. Check whether there are more words than the amount allowed. If so, remove all the excess words: while (text.length > maxWords). Then just replace the value of the text box with the updated text.

JavaScript $ b

JavaScript

var maxWords = 10;
$("#myText").keypress(function (event) {
    var text = $(this).val().split(" ");    // grabs the text and splits it
    while (text.length > maxWords) {        // while more words than maxWords
        event.preventDefault();
        text.pop();    // remove the last word
        // event.preventDefault() isn't absolutely necessary,
        // it just slightly alters the typing;
        // remove it to see the difference
    }
    $(this).val(text.join(" "));    // replace the text with the updated text
})



HTML

HTML

<p>Enter no more than 10 words:</p>
<textarea id="myText"></textarea>

CSS

CSS

textarea {
    width: 300px;
    height: 100px;     
}

您可以通过粘贴 maxWords - 在这种情况下, 10 - 进入 textarea 并按空格。所有额外的单词将被删除。

You can easily test whether it works by pasting more than maxWords—in this case, 10—words into the textarea and pressing space. All the extra words will be removed.

这篇关于从文本框中删除多余的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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