Reputation: 495
I'm trying to do a regex which accepts a string containing 3-10 characters (white spaces before and after the string are allowed).
Why does this:
return (this.state.user.name.match(`^\s*([a-zA-Z0-9.\-_]{3,10})\s*$`));
returns false when I try to put white space(s) before and/or after the string? (it works correctly if I don't put white spaces.)
I am probably missing something, because it works using the regex tester: https://regex101.com/r/2371SM/1
Thanks for your help.
Upvotes: 0
Views: 41
Reputation: 64657
When you pass the regex as a string you have to do double \\
so that you are escaping the \
and not the letter that follows it:
console.log(((" abcd").match(`^\\s*([a-zA-Z0-9.\-_]{3,10})\\s*$`)));
console.log(((" abcd").match(/^\s*([a-zA-Z0-9.\-_]{3,10})\s*$/)));
Upvotes: 3