Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

javascript - word count method

I have recently used modified a word count method in javascript for my website, so that it counts the intial amount words in the textarea, but it doesn't quite work

function wordCounter(field,countfield)
{
    var maxlimit = 200;
    var wordcounter = maxlimit - information.value.split(' ').length;
    for (x = 0; x < field.value.length; x++) 
    {
        if(field.value.charAt(x) == " " && field.value.charAt(x-1) != " ") // Counts the spaces while ignoring double spaces, usually one in between each word.
        {
            wordcounter++ 
        }

        if (wordcounter > 250) 
        {
            field.value = field.value.substring(0, x);
        }
        else
        {
            countfield.value = maxlimit - wordcounter;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Given string "s", you do this:

var numWords = s.replace(/^s+|s+$/g,"").split(/s+/).length;

This splits the string at all whitespaces (spaces, linebreaks etc), also working with multiple spaces etc. EDIT: added inline trim to strip whitespace from beginning/end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...