简体   繁体   中英

JavaScript RegExp pattern

I have a string like below...

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

Now how can I replace all the white spaces with underscore only inside "" using RegExp so that the string looks like below...

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

so that by using .replace('"','').split(' ') , I can get an array like below...

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

no jQuery please...

You want to replace each string within the input string by another string by replacing spaces with underscores within the string. You can use a replace with callback to do that:

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'

I know this has been answered but I thought I'd share this regex using a positive look-ahead. This allows you to replace without using a callback.

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

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

To explain:

\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

Then the g will repeat the search

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

Choose the one you need:

Object:

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"
// }

Array:

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

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