Javascript regex match for string “game_1”
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.
My question was:
I just can’t get this thing to work in javascript. So, I have a text “game_1” without the quotes and now i want to get that number out of it and I tried this:
var idText = "game_1"; re = /game_(.*?)/; found = idText.match(re); var ajdi = found[1]; alert( ajdi );
But it doesn’t work – please point out where am I going wrong.
The answer, by Naltharial, was:
If you’re only matching a number, you may want to try
/game_([0-9]+)/as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (
*
) and let it select the shortest possible result (?
), which may be a problem (and match you 0 characters), depending on the regex engine.
Leave a Comment