I want to replace
$addCmdReactions[test]
to
test
I know the regex (/\$addCmdReactions/i
) but I don't know how to replace it
CodePudding user response:
I'm assuming all you want to do is remove the "$addCmdReactions[]" part.
You could use string .replace but you can also use .exec
on the RegEx expression to extract whatever is between the square brackets. This could be useful as it's a bit more dynamic and cleaner and easily extendible depending on the kind of match you want.
See below
const text = '$addCmdReactions[test]';
const matches = /\$addCmdReactions\[(. )\]/g.exec(text);
console.log(matches);
console.log(matches[1]); // "test" - Has the first match from the (. )
CodePudding user response:
@Azarro's solution works fine for a single occurrence but will return wrong results when multiple $addCmdReactions[test]
s are to be replaced.
The following will work with any number of replacements:
const text = '$addCmdReactions[test] and $addCmdReactions[toast].';
console.log(text.replace(/\$addCmdReactions\[([^\]] )\]/g,"$1"));
// Azarro's approach:
const matches = /\$addCmdReactions\[(. )\]/g.exec(text);
console.log("Azarro:", matches);