2

I have a javascript string variable like so:

var somestring = "mypattern_var1_var2";

How can I use regex to extract var1 & var2?

4 Answers 4

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];
Sign up to request clarification or add additional context in comments.

Comments

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];

Comments

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

3 Comments

Haha barely! You deserve an upvote too. It gets crazy when each answer is within seconds of each other.
@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 ;)
Hahaha it's not a true javascript question if jQuery isn't mentioned. I do love me some jQuery though!
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

Comments

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.