Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS how to check empty String and Space [duplicate]

Help me pls

if(value == ""){
// do anything
}

but I need to check space " " (2,3,... space is include) is the same way of empty String

ps. sorry in my English

like image 334
JinkleBell Surcharoen Avatar asked Apr 08 '16 03:04

JinkleBell Surcharoen


People also ask

How do you check if a string contains a space in JS?

/^\s+$/ is checking whether the string is ALL whitespace: ^ matches the start of the string. \s+ means at least 1, possibly more, spaces.

Is empty string whitespace?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.


1 Answers

A regex can easily solve this problem.

if (/^ *$/.test(value)) {
    //string contains 0+ spaces only
}

If you need to include null also, then add !value ||.

If you need to include newlines, tabs, and the like, then use /^\s*$/ for the regex.

like image 88
4castle Avatar answered Oct 27 '22 13:10

4castle