I want to take a string and remove all occurrences of characters within square brackets:
[foo], [foo123bar], and [123bar] should be removed
But I want to keep intact any brackets consisting of only numbers:
[1] and [123] should remain
I’ve tried a couple of things, to no avail:
text = text.replace(/\[^[0-9+]\]/gi, "");
text = text.replace(/\[^[\d]\]/gi, "");
The tool you’re looking for is negative lookahead. Here’s how you would use it:
After
\[locates an opening bracket, the lookahead,(?!\d+\])asserts that the brackets do not contain only digits.Then,
[^\[\]]+matches anything that’s not square brackets, ensuring (for example) that you don’t accidentally match “nested” brackets, like[[123]].Finally,
\]matches the closing bracket.