This deals with the general problem of extracting a signed number from a string that also contains hyphens.

Can someone please come up with the regex for the following:

 "item205"             => 205  
 "item-25              => -25  
 "item-name-25"        => -25  

Basically, we want to extract the number to the end of the string, including the sign, while ignoring hyphens elsewhere.

The following works for the first two but returns "-name-25" for the last:

var sampleString = "item-name-25";
sampleString.replace(/^(\d*)[^\-^0-9]*/, "")

Thanks!

share|improve this question

71% accept rate
2  
Any particular reason this was voted down? Seems perfectly valid... – Randy Hall Dec 7 '12 at 17:40
feedback

2 Answers

up vote 4 down vote accepted

You can use .match instead:

"item-12-34".match(/-?\d+$/);  // ["-34"]

The regexp says "possible hyphen, then one or more digits, then the end of the string".

share|improve this answer
feedback

Don't use replace. Instead, use match and write the regex for what you actually want (because that's a lot easier):

var regex = /-?\d+$/;
var match = "item-name-25".match(regex);
> ["-25"]
var number = match[0];

One thing about your regex though: in a character class you can only meaningfully use ^ once (right at the beginning) to mark it as a negated character class. It doesn't work for every single element individually. That means that your character class actually corresponds to "any character that is not a -, ^ or a digit.

share|improve this answer
Was just about to post this. Hah. – Shmiddty Dec 7 '12 at 17:42
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.