2

I have a javascript string variable like so:

var somestring = "mypattern_var1_var2";

How can I use regex to extract var1 & var2?

hitautodestruct
  • 20,081
  • 13
  • 69
  • 93
VinnyD
  • 3,500
  • 9
  • 34
  • 48

4 Answers4

3

I would just use the split() method instead if it's that straightforward:

var somestring = "mypattern_var1_var2";
var tokens = somestring.split("_");
var var1 = tokens[1];
var var2 = tokens[2];
McStretch
  • 20,495
  • 2
  • 35
  • 40
2

No need

var parts = somestring.split("_");
alert(parts[1] + ':' + parts[2])

Or get real fancy like How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

And we MUST have jQuery in the equation: Regular expression field validation in jQuery

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Haha barely! You deserve an upvote too. It gets crazy when each answer is within seconds of each other. – McStretch Mar 29 '11 at 19:32
  • @McStr - so now we should add a fiddle to demo this complex script. I wonder if we can't make it more interesting with a jQuery plugin and `each` ;) – mplungjan Mar 29 '11 at 19:35
  • 1
    Hahaha it's not a true javascript question if jQuery isn't mentioned. I do love me some jQuery though! – McStretch Mar 29 '11 at 19:39
2

I know you specified regex, but is there a specific reason to use it?

An alternative would be to use the .split() method, which would probably be easier.

var somestring = "mypattern_var1_var2";
var results = somestring.split("_");

var var1 = results[1];
var var2 = results[2];
Brandon
  • 68,708
  • 30
  • 194
  • 223
1

You could use a split() in this situation - given that you always know that you will have a pattern in the beginning, (given that the pattern doesn't contain any '_'s)

var somestring = "mypattern_var1_var2";
var example = somestring.split('_');

var1 = example[1];
var2 = example[2];

Demo

Rion Williams
  • 74,820
  • 37
  • 200
  • 327