alert($(this)[0]); returns a url, eg. http://localhost/www/anotherdir/go.php?id=12aaa
I wish to place the “12” and the “aaa” into separate vars (quoted vals could be anything, but will always be a number followed by three alpha).
Using the regex /\?* returns id=12aaa in a regex editor, but…
This does not generate an alert() box – nothing happens at all:
x = $(this)[0].match(/\?*/);
alert(x);
This also does not do anything:
x = $(this)[0].match(/\?*/);
alert(x[0]);
Try this:
Pretending that $(this)[0] returns “/my/fun/path?query1=a&query2=b
Note that
xwill be the array["query1=a&query2=b"]If you, for instance, wanted to get each query parameter as an index in an array you could do this:
Which will give you:
Editing to break-down the regex for you:
[]is a character class, and can only ever match one single character no matter how much contents it has.[a-z]for instance, will match any single lower-case alphabetic character.^(caret) at the beginning of the character class is a not-identifier. Indicating that this character class has an opposite effect – it will match any single character that does NOT match the rest of the contents. This position (first character in a character class) is the only time that the caret indicates ‘not’. In other contexts it has a different meaning (For instance, at the beginning of your regex the^will indicate that the beginning of the string must start there).[^\?]indicates that we will match any single character that is not a question markalert(x[0])should have output an empty dialog, more on that later$at the end of the reg-ex states “End of string” which means… of course, that the end of the string must be at that point.Therefore we know the regex will not collect the question mark from your url because then it would not be able to hit the end of the string while still collection multiple non-question marks. The
*is always greedy unless otherwise specified, so it will get as many characters as possible.Your alert(x[0]) should have output an empty alert (I tested it, and it did for me) because the .match() method matches the first thing it can, since
/\?*/matches virtually every single string possible it must have stopped after seeing the first character and saying “oh there’s a match here!”Hopefully this was helpful for your understanding 🙂 Regexes can be confusing when you start out with them but I absolutely love ’em. So powerful.