JavaScript RegExp模式

时间:2012-11-21 06:20:46

标签: javascript regex string

我有一个像下面的字符串......

var1=val1 var2=val2 var3="p1 p2 p3 p4" var4="p1 p2" var5=val5

现在,如何使用RegExp仅在white spaces内替换所有underscore "",以便字符串如下所示...

var1=val1 var2=val2 var3="p1_p2_p3_p4" var4="p1_p2" var5=val5

这样通过使用.replace('"','').split(' '),我可以获得如下的数组......

Array(
   var1: "val1",
   var2: "val2",
   var3: "p1_p2_p3_p4",
   var4: "p1_p2",
   var5: "val5"
)

请不要jQuery ...

4 个答案:

答案 0 :(得分:2)

您希望通过用字符串中的下划线替换空格来将输入字符串中的每个字符串替换为另一个字符串。您可以使用替换回调来执行此操作:

var inp='var1=val1 var2=val2 var3="p1 p2 p3 p4" var4="p1 p2" var5=val5'

var outp=inp.replace(/"[^"]*"/g, function(x){
  return x.replace(/ /g, '_');
})

// var outp === 'var1=val1 var2=val2 var3="p1_p2_p3_p4" var4="p1_p2" var5=val5'

答案 1 :(得分:2)

我知道这已经得到了解答,但我认为我会使用积极的预测来分享这个正则表达式。这允许您在不使用回调的情况下replace

var str = 'var1=val1 var2=val2 var3="p1 p2 p3 p4" var4="p1 p2" var5=val5';

str = str.replace(/\s(?=[^=]*")/g, '_');

解释:

\s        match a space...
(?=       start of positive look-ahead
[^=]*"    ...which is followed by anything except an =, up to a double-quote
)         end of positive look-ahead

然后g将重复搜索

答案 2 :(得分:1)

var arr = string.replace(/(=")([^"]*)(")/g,function(m,g1,g2,g3){return g1 + g2.replace(/ /g, "_") + g3;}).split(' ');

答案 3 :(得分:0)

选择您需要的那个:

对象:

var txt = 'var1=val1 var2=val2 var3="p1_p2_p3_p4" var4="p1_p2" var5=val5',
    arr = txt.split(" "),
    obj = {};

for(var i = 0 ; i < arr.length; i++){
    var ind = arr[i].match(/^(.+)=/)[1],
        val = arr[i].match(/=(.+)$/)[1].replace(/_/g," ");
    obj[ind] = val;
}

console.log(obj);  //This will give you an object.
// {
//     var1: "val1",
//     var2: "val2",
//     var3: ""p1 p2 p3 p4"",
//     var4: ""p1 p2"",
//     var5: "val5"
// }

阵列:

var txt = 'var1=val1 var2=val2 var3="p1_p2_p3_p4" var4="p1_p2" var5=val5',
    arr = txt.split(" "),
    list = [];

for(var i = 0 ; i < arr.length; i++){
    var val = arr[i].match(/=(.+)$/)[1].replace(/_/g," ");
    list.push(val);
}

console.log(list);  //This will give you an array.
// [
//     "val1",
//     "val2",
//     ""p1 p2 p3 p4"",
//     ""p1 p2"",
//     "val5"
// ]