Filtering “whitespace-only” strings in JavaScript

前端 未结 4 1659
被撕碎了的回忆
被撕碎了的回忆 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:39

    The trim() method on strings does exist in the ECMAScript Fifth Edition standard and has been implemented by Mozilla (Firefox 3.5 and related browsers).

    Until the other browsers catch up, you can fix them up like this:

    if (!('trim' in String.prototype)) {
        String.prototype.trim= function() {
            return this.replace(/^\s+/, '').replace(/\s+$/, '');
        };
    }
    

    then:

    if (inputString.trim()==='')
        alert('white junk');
    
    0 讨论(0)
  • 2020-12-20 14:51

    Alternatively, /^\s*$/.test(inputString)

    0 讨论(0)
  • 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'.

    0 讨论(0)
  • 2020-12-20 15:02
    function trim (myString)
    {
        return myString.replace(/^\s+/,'').replace(/\s+$/,'')
    } 
    

    use it like this: if (trim(myString) == "")

    0 讨论(0)
提交回复
热议问题