Login Register


REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER filter_list
Author
Message
REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER #1
Why am I so stupid? I need to test one character.
Regex has scared me for so long, I really don't know what I'm doing.
I'm writing a parser, so I'm only testing one character at a time.
the block of code I'm working with "knows" it's about to work on a variable. (or expects to)
For the first character in that variable I need to determine if it's $, _ or abc(a letter).
Code:
if( /\w_$/g.test( _.getCurr() ) )
This, does not work. It doesn't match for $
(This post was last modified: 04-06-2017, 03:46 PM by FractalBomb.)

Reply

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

RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER #3
I tried this /([A-Z]_?\$?)+$/ig and it works for myself. I would recommend using the one above mine though being as I didn't really test mine that much o-O
Also I didn't read your question that heavily, too tired to read D:

Reply

RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER #4
I'm not even going to test it, but thanks!
It looks very legit and I would recommend.
BTW, HOW LONG DID IT TAKE FOR YOU TO MAKE THIS?
(This post was last modified: 04-17-2017, 06:40 PM by Shin.)
[Image: hJkWWcF.png]

Reply

RE: REGEX FOR VALID JAVASCRIPT VARIABLE IN 1ST CHARACTER #5
I got my issue fixed. thanks

Reply







Users browsing this thread: 1 Guest(s)