最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Extract embedded number from string - JavaScript Regex - Stack Overflow

programmeradmin3浏览0评论

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

Can someone please e 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!

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

Can someone please e 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 edited Dec 12, 2012 at 12:35 Zephyr asked Dec 7, 2012 at 17:32 ZephyrZephyr 7,8234 gold badges39 silver badges41 bronze badges 1
  • 2 Any particular reason this was voted down? Seems perfectly valid... – Randy Hall Commented Dec 7, 2012 at 17:40
Add a ment  | 

2 Answers 2

Reset to default 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".

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.

发布评论

评论列表(0)

  1. 暂无评论