Filtering “whitespace-only” strings in JavaScript

前端 未结 4 1658
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 14:34

I have a textbox collecting user input in my JS code. I would like to filter junk input, like strings that contain whitespaces only.

In C#, I would use the following

4条回答
  •  生来不讨喜
    2020-12-20 14:57

    Use a regular expression:

    if (inputString.match(/^\s*$/)) { alert("not ok"); }
    

    or even easier:

    if (inputString.match(/\S/)) { alert("ok"); }
    

    The \S means 'any non white space character'.

提交回复
热议问题