2

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!

1
  • 2
    Any particular reason this was voted down? Seems perfectly valid... Commented Dec 7, 2012 at 17:40

2 Answers 2

6

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".

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

Was just about to post this. Hah.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.