javascript正则表达式匹配模式后获取字符串

时间:2022-09-13 00:23:34

I have a string that looks like this:

我有一个看起来像这样的字符串:

var str = "fname=peter lname=pan age=12"

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

我需要的是获取一个字符串数组,每个字符串在fname或lname或age之后,在str变量之外。结果如下:['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 个解决方案

#1


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

#2


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

演示

#3


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

#1


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

#2


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

演示

#3


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