2

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?

Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476

1 Answers1

3

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));
 
Tim Biegeleisen
  • 451,927
  • 24
  • 239
  • 318