What does this "/^\s*$/" mean as I tried to learn it from here: but can't get it meaning?
fn: function (val) {
return typeof val === 'string' ?
!/^\s*$/.test(val) : val !== undefined && val !== null;
}
What does this "/^\s*$/" mean as I tried to learn it from here: https://developer.mozilla/en/docs/Web/JavaScript/Guide/Regular_Expressions but can't get it meaning?
fn: function (val) {
return typeof val === 'string' ?
!/^\s*$/.test(val) : val !== undefined && val !== null;
}
Share
Improve this question
asked Jan 7, 2017 at 18:58
Kavish MehtaKavish Mehta
532 silver badges9 bronze badges
4
- From the URL you wrote: ^ : Matches beginning of input. \s : Matches a single character other than white space. * : Matches the preceding expression 0 or more times. $ : Matches end of input. 1+2+3+4 : Matches a string that begin and end with 0 or many white spaces. – progysm Commented Jan 7, 2017 at 19:01
- @KavishMehta, did you accept and then unaccept my answer? Is there anything else unclear? – Max Koretskyi Commented Jan 7, 2017 at 19:35
- @Maximus sorry I double click it – Kavish Mehta Commented Jan 7, 2017 at 19:49
- @KavishMehta, no problem, just wondered if it was a glitch, good luck) – Max Koretskyi Commented Jan 7, 2017 at 20:00
3 Answers
Reset to default 4This
/^\s*$/
is a RegExp object
The code snippet
/^\s*$/.test(val)
uses RegExp test method to test whether a string val
is empty or only contains spaces. From the docs:
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
If you take a look at this regex in this tutorial, it will show you the following explanation:
^ asserts position at start of the string
\s* matches any whitespace character (equal to [\r\n\t\f\v ])
* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)
Basically, it means that:
/^...$/
matches a string from the beginning to the end, and
\s*
matches zero or more occurrences of white space characters
Here ^ means the beginning of expression.
\s* means 0 or more occurrences of space characters(' ', tab etc)
$ means end of the string.
so /^\s*$/
is the regex for empty string or string with only spaces.
/^\s*$/
first /{regex is here}/ is how u write regex here
^{somethingelse}$ is meaning started and ended in the middle regex
\s is any string character
'*' means zero or more
so it means all the element is character, not a number or symbol or spaces