0

I need to capture a number passed as appended integers to a CSS class. My regex is pretty weak, what I'm looking to do is pretty simple. I thought that "negative word boundary" \B was the flag I wanted but I guess I was wrong

string = "foo bar-15";
var theInteger = string.replace('/bar\-\B', ''); // expected result = 15
Brian
  • 3,920
  • 12
  • 55
  • 100

4 Answers4

3

Use a capture group as outlined here:

var str= "foo bar-15";
var regex = /bar-(\d+)/;
var theInteger = str.match(regex) ? str.match(regex)[1] : null;

Then you can just do an if (theInteger) wherever you need to use it

Community
  • 1
  • 1
JamesSwift
  • 863
  • 1
  • 7
  • 16
  • The problem here is that if there are no trailing digits, `match` returns `null` and attempting to access `null[1]` will throw an error. Better to first call `match`, then check the result before going further (see my answer). – RobG Oct 24 '12 at 02:17
  • Even prettier is `theInteger = str.match(regex) ? RegExp.$1 : null` – Sean Kinsey Oct 24 '12 at 02:24
  • 1
    @SeanKinsey—let's get silly. If `null` is an OK result, then `theInteger = str.match(regex) && RegExp.$1;` is prettiest (so far). – RobG Oct 24 '12 at 03:37
  • @RobG, sure I just hate misusing the && operator as a conditional operator. – Sean Kinsey Oct 24 '12 at 03:49
  • Hey, Crockford says it's OK as the ["guard"](http://www.crockford.com/javascript/survey.html), so that gives me *carte blance*, doesn't it? ;-) – RobG Oct 24 '12 at 05:10
  • Thanks for thinking it through so much @JamesSwift - looks great :) – Brian Oct 24 '12 at 16:01
1

Try this:

var theInteger = string.match(/\d+/g).join('')
Ram
  • 143,282
  • 16
  • 168
  • 197
  • Nah - I want to be future-proof against other integer-based classes being introduced into the CSS. Matching the "bar-" characters and removing them to get the integer is necessary. – Brian Oct 24 '12 at 00:23
1
string = "foo bar-15";
var theInteger = /bar-(\d+)/.exec(string)[1]
theInteger // = 15
Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
1

If you just want the digits at the end (a kind of reverse parseInt), why not:

var num = 'foo bar-15'.replace(/.*\D+(\d+)$/,'$1');

or

var m = 'foo bar-15'.match(/\d+$/);
var num = m? m[0] : '';
RobG
  • 142,382
  • 31
  • 172
  • 209