Reputation: 1826
I have a string that looks like this:
var str = "fname=peter lname=pan age=12"
What I need is to get an array of string, each of that string goes right after fname or lname or age, out of str variable. The result is like this: ['peter', 'pan', '12']
.
Could you suggest me an effective solution to accomplish that task (I got a long one, and believe me you would never wanna see that)?
Thank you!
Upvotes: 0
Views: 1784
Reputation: 69934
You could also consider hardcoding the keys to avoid looping:
var s = "fname=peter lname=pan age=12"
var pat = /fname=(\w+)\s*lname=(\w+)\s*age=(\w+)/
r.match(pat)
//returns ["fname=peter lname=pan age=12", "peter", "pan", "12"]
Upvotes: 0
Reputation: 94101
Try:
var arr = [];
str.replace(/=(\w+)/g, function( a,b ) {
arr.push( b );
});
console.log( arr ); //=> ["peter", "pan", "12"]
Here's another way to do it with similar regex:
var arr = str.match(/=\w+/g).map(function( m ){
return m.replace('=','');
});
Upvotes: 2
Reputation: 26320
You don't need a regex
.
var str = "fname=peter lname=pan age=12";
str = str.split(' ');
for(var i = 0, length = str.length; i < length; i++) {
str[i] = str[i].split('=')[1];
}
console.log(str); // ['peter', 'pan', '12']
Upvotes: 1