Login Register


REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER filter_list
Author
Message
RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER #2
I'm a bit late here, but this doesn't work for a few reasons.

First, because "$" matches the end of the test string (or the line if you're using the multiline "m" modifier). To match the $ character literally, you need to escape it ("\$").
Second, you're not using character ranges. Your current pattern tries to match a letter, then an underscore, then the end of the string via $ instead of any of those.
Third, it's pretty inefficient. If you're testing the first character of a string, why not just do that and eliminate the unnecessary function call? Just use a caret at the beginning to match the start of a string (opposite of $).

Finally, you don't need the global modifier since you're not looking for multiple (or any) matches. A working (and more efficient) regex pattern is included below.
The $ doesn't need escaping because it's in the range, which treats all characters as literal.

Code:
/^[a-zA-Z_$]/.test(fullString)

I highly recommend regex 101 to anyone who uses regular expressions often. It's a great visual tester and has tons of resources and reference for learning. Hell, I still use it weekly. Regex is hard, but it's a valuable skill to have, don't get too discouraged.
(This post was last modified: 04-11-2017, 07:58 PM by Inori.)
It's often the outcasts, the iconoclasts ... those who have the least to lose because they
don't have much in the first place, who feel the new currents and ride them the farthest.

Reply





Messages In This Thread
RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER - by Inori - 04-11-2017, 07:57 PM



Users browsing this thread: