Regular Expression for accurate word-count using JavaScript

后端 未结 7 1010
陌清茗
陌清茗 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:26

    Try

        value.match(/\w+/g).length;
    

    This will match a string of characters that can be in a word. Whereas something like:

        value.match(/\S+/g).length;
    

    will result in an incorrect count if the user adds commas or other punctuation that is not followed by a space - or adds a comma with a space either side of it.

提交回复
热议问题