Help us understand the problem. What is going on with this article?

JavaScriptで空白や改行のみの場合も空文字判定する方法

textareaやinputタグで空文字判定をしたい場面があるかと思います。
その場合、

    <textarea id="text"></textarea>
    <script>
        var text = document.getElementById('text')
    </script>
text.value === ''
!text.value

などで空文字判別を行うことができます。
しかし、これだと空白(スペース)や改行があった場合に空文字では無くなってしまいます。

その時は、matchメソッドを使うことで、空白や改行があっても空文字判定が可能です。

!text.value.match(/\S/g))

\Sは空白文字(半角スペース、\t、\n、\r、\f)以外全てのことです。

!text.value || !text.value.match(/\S/g)

!text.valueと組み合わせることで、何も入力されていない時、空白や改行のみの入力の場合など合わせて空文字判定をおこなうことができます。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away