Regular Expression for accurate word-count using JavaScript

后端 未结 7 1011
陌清茗
陌清茗 2020-12-01 07:15

I\'m trying to put together a regular expression for a JavaScript command that accurately counts the number of words in a textarea.

One solution I had found is as fo

7条回答
  •  死守一世寂寞
    2020-12-01 07:36

    For me this gave the best results:

    value.split(/\b\W+\b/).length
    

    with

    var words = value.split(/\b\W+\b/)
    

    you get all words.

    Explanation:

    • \b is a word boundary
    • \W is a NON-word character, capital usually means the negation
    • '+' means 1 or more characters or the prefixed character class

    I recommend learning regular expressions. It's a great skill to have because they are so powerful. ;-)

提交回复
热议问题