Zephyr
Zephyr

Reputation: 7823

Extract embedded number from string - JavaScript Regex

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!

Upvotes: 2

Views: 2384

Answers (2)

Martin Ender
Martin Ender

Reputation: 44279

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.

Upvotes: 4

pimvdb
pimvdb

Reputation: 154918

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

Upvotes: 6

Related Questions