开发者

Javascript regex match for string "game_1"

开发者 https://www.devze.com 2023-03-17 17:41 出处:网络
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:

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";
开发者_Go百科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.


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.


If this is the complete text, then there is no need for regular expressions:

var id = +str.split('_')[1];

or

var id = +str.replace('game_', '');

(unary + is to convert the string to a number)


If you insist on regular expression, you have to anchor the expression:

/^game_(.*?)$/

or make the * greedy by omitting the ?:

/game_(.*)/

Better is to make the expression more restrictive as @Naltharial suggested.


Simple string manipulation:

var idText = "game_1",
    adji = parseInt(idText.substring(5), 10);


* means zero or more occurrences. It seems that combining it with a greediness controller ? results in zero match.

You could replace * with + (which means one or more occurrences), but as @Felix Kling notes, it would only match one digit.

Better to ditch the ? completely.

http://jsfiddle.net/G8Qt7/2/


Try "game_1".replace(/^(game_)/, '')
this will return the number


You can simply use this re /\d+/ to get any number inside your string

0

精彩评论

暂无评论...
验证码 换一张
取 消