0

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?

Edie Johnny
  • 513
  • 2
  • 5
  • 14

3 Answers3

1

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

strname.trim().length == 0
Chris Barlow
  • 466
  • 4
  • 8
  • This way? $(this).trim().length > 0 But it returned an error, trim needs an argument, shouldn't it be trim($(this)).length > 0 ? – Edie Johnny Sep 18 '14 at 23:11
  • trim is a method of a string. Is $(this) a string? Maybe $(this).toString().trim().length depending on the type of this. Or $(this).value. – Chris Barlow Sep 18 '14 at 23:17
  • Looking at your question, if $(this) is a textarea, you probably want $(this).value. – Chris Barlow Sep 18 '14 at 23:18
1

You check it like this: demo on JSexample

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

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

if (!!str.replace(/\s/g, '').length) {
    alert('only spaces')
}
Tengiz
  • 1,902
  • 14
  • 12