Using regex to remove key value in string

Viewed 215

I have a string in the form of [stringKey1:stringValue1][stringKey2:stringValue2][stringKey3:stringValue3].

I'm having trouble using regex to remove the the string between [] using a stringKey.

What Im trying to do is

const string = "[stringKey1:stringValue1][stringKey2:stringValue2][stringKey3:stringValue3]";

const newString = removeStringKey("stringKey2");

newString === "[stringKey1:stringValue1][stringKey3:stringValue3]"

Any suggestions?

1 Answers

Use a regex replacement:

function removeStringKey(key, input) {
    var re = new RegExp("\\[" + key + ":.*?\\]");
    return input.replace(re, "");
}

const string = "[stringKey1:stringValue1][stringKey2:stringValue2][stringKey3:stringValue3]";
console.log(removeStringKey("stringKey2", string));
 

Related