简体   繁体   English

从文本框中删除多余的单词

[英]Remove excess words from a textbox

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? 例如,如果您输入102个单词,那么超出的部分将为2。我如何从文本区域中删除这两个单词?

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

        }
    });         
});

well it would be better to use java script so here you go: 好吧,使用Java脚本会更好,所以在这里:

var maxWords = 20;
event.rc = true;
var words = event.value.split(" ");
if (words.length>maxWords) {
    app.alert("You may not enter more than " + maxWords + " words in this field.");
    event.rc = false;
}

You can put below code into your else if statement.. 您可以将以下代码放入您的else if语句中。

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

And if you want to get your string back from that words , you can use join like below: 而且,如果您想从这些words找回字符串,则可以使用join如下所示:

str = words.join(' ');

The easiest way to approach this is just to count the number of words on keypress and go from there. 解决此问题的最简单方法就是计算keypress上的单词数并从那里开始。 Check whether there are more words than the amount allowed. 检查单词数是否超过允许的数量。 If so, remove all the excess words: while (text.length > maxWords) . 如果是这样,请删除所有多余的单词: while (text.length > maxWords) Then just replace the value of the text box with the updated text. 然后,用更新后的文本替换文本框的值。

fiddle 小提琴

JavaScript 的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;     
}

You can easily test whether it works by pasting more than maxWords —in this case, 10 —words into the textarea and pressing space. 您可以通过在textarea粘贴多个maxWords在本例中为10 maxWords并按空格来轻松测试其是否有效。 All the extra words will be removed. 所有多余的单词将被删除。

jsFiddle Demo jsFiddle演示

You can use val to re-value the text-box. 您可以使用val重新估价文本框。 The array slice method will allow you to pull the first 100 words out of the array. 数组slice方法将允许您从数组中拉出前100个单词。 Then just join them with a space and stick them back in the text-box. 然后,只需在空格处加入它们,然后将其粘贴回文本框中即可。

$(document).ready(function($) {
    var max = 100;

    $('#text').keyup(function(e) {

        if (e.which < 0x20) {
            return;
        }

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

        if (wordCount == max) {
            // Reached max, prevent additional.
            e.preventDefault();
        } else if (wordCount > max) {
            var substring = words.slice(0, max).join(' ');
            $("#text").val(substring + ' ');
        }
    });         
});

While you've already accepted an answer I thought I might be able to offer a slightly more refined version: 虽然您已经接受了答案,但我认为我也许可以提供稍微完善一些的版本:

function limitWords(max){
    // setting the value of the textarea:
    $(this).val(function(i,v){
    // i: the index of the current element in the collection,
    // v: the current (pre-manipulation) value of the element.

    // splitting the value by sequences of white-space characters,
    // turning it into an Array. Slicing that array taking the first 10 elements,
    // joining these words back together with a single space between them:
        return v.split(/\s+/).slice(0,10).join(' ');
    });
}

$('#demo').on('keyup paste input', limitWords);

JS Fiddle demo . JS小提琴演示

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM