Edie Johnny
Edie Johnny

Reputation: 523

How to test if a string has only spaces in Javascript?

I have a textarea and I need to test if the user put a text like "                        ", or only spaces in it or only " ", I can't accept only spaces, but I can accept "         Hi    !!". How can I do this in Javascript?

Upvotes: 0

Views: 1906

Answers (3)

Tengiz
Tengiz

Reputation: 1920

Be careful, some browsers don't support trim() function. I'd use like this:

if (!!str.replace(/\s/g, '').length) {
    alert('only spaces')
}

Upvotes: 0

ehall007
ehall007

Reputation: 21

You check it like this: demo on JSexample

<script>
    var text = '          '
    if(text.match(/^\s*$/)){
        alert('contains only spaces!')
    }
</script>

Upvotes: 1

Chris Barlow
Chris Barlow

Reputation: 466

Just trim it and the length will be 0 if it is all spaces.

strname.trim().length == 0

Upvotes: 1

Related Questions