简体   繁体   中英

javascript regular expression get string after matched pattern

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!

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('=','');
});

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM