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?

3 Answers 3

1

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

strname.trim().length == 0
Sign up to request clarification or add additional context in comments.

3 Comments

This way? $(this).trim().length > 0 But it returned an error, trim needs an argument, shouldn't it be trim($(this)).length > 0 ?
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.
Looking at your question, if $(this) is a textarea, you probably want $(this).value.
1

You check it like this: demo on JSexample

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.