简体   繁体   中英

Javascript regex extract with variable

I'd like to extract values from below key:value pairs being sent in as a single string:

"var1:value1,var2:value2,var3:value3"

I have to use JavaScript and unfortunately I am unable to use an array and loop through the var1,var2,var3 keys due to the regex unable to handle variables... I am wondering if there is a way to do this in JS?

See below:

function onBefore(current, previous) 
{
if (current.key != '' || current.key != null) 
{
    if (current.key.match(/var1/)) {
    var assign = current.key.match(/(?:var1:)([^,]+)/)[1];
    } else if (current.key.match(/var2/)) {
    var assign = current.key.match(/(?:var2:)([^,]+)/)[1];
    } else if (current.key.match(/var3/)) {
    var assign = current.key.match(/(?:var3:)([^,]+)/)[1];
    } else if (current.key.match(/var4/)) {
    var assign = current.key.match(/(?:var4:)([^,]+)/)[1];
    }
    } else {
        assign = "None";
    }
    if (assign != "None") {
    current.node = assign;
    }
}
}

@revo thanks for that answer, for others to benefit... here's the final code:

  var str = "keyIcareabout:test3end,something:value,nothing:burger"; var node = "None"; function valueOf(key) { return (m = (new RegExp("\\\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null; } if (str != '' || str !== null) { var resources = ["keyIcareabout","somethingelseIcareabout"]; for (i = 0; i < resources.length; i++) { if (str.match(resources[i])) { node = valueOf(resources[i]); } } } if (node != "None") { console.log("Matched " + node + " with node field "); } 

Use String.split :

 const data = 'var1:value1,var2:value2,var3:value3'; const pairStrings = data.split(/,/g); const pairs = pairStrings.map(pairString => pairString.split(/:/)); const object = pairs.reduce((object, [key, value]) => { object[key] = value; return object; }, {}); console.log(object); 

You underestimated RegEx. Your whole function could be shorten to this:

function valueOf(key) {
   return (m = (new RegExp("\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null;
}

You don't have to check for each key individually in an if condition. Pass key to above valueOf() function to retrieve the value.

 var str = "aws_acnt_name:test,aws_acnt_num:1234," + "host:identity01.auth-test,region:us-west-2,snow_sg:aws_cloud"; function valueOf(key) { return (m = (new RegExp("\\\\b" + key + ":([^,]+)")).exec(str)) !== null ? m[1] : null; } console.log(valueOf('host')); console.log(valueOf('aws_acnt_name')); 

You can use a regex RegExp.exec() to loop through matches of key/value pairs, and extract the key and value to an object (or an array):

 var str = 'var1:value1,var2:value2,var3:value3'; var pattern = /([^:,]+):([^,]+)/g; var obj = {}; var temp; while(temp = pattern.exec(str)) { obj[temp[1]] = temp[2]; } console.log(obj); 

Edit- deleting my answer as suggested by vasan, we need to have quotes around the key and values. Rather than adding quotes and then parsing it will be better to just split it using split function. So SimpleJ's answer should work.

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