0

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!

3 Answers 3

2

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('=','');
});
Sign up to request clarification or add additional context in comments.

2 Comments

This is a better way to do it, using regexp is always more efficient and more clean than using split method and for cycles. Just make sure to return the matched string b at the end of the function if you don't want to modify the str variable.
replace doesn't mutate the original string.
1

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

demo

Comments

0

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

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.