benbyford
benbyford

Reputation: 649

Javascript REGEX matching two brackets [[something]]

trying to match anything width and including two brackets e.g. [[match this]] so I can replace without brackets.

here is what I have as far var regex = /([\[\|\]])\w+/g;

However this matches the above like this [match

Any help would be appreciated

Upvotes: 1

Views: 2184

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626802

Your ([\[\|\]])\w+ matches 1 symbol - [, | or ] (with ([\[\|\]])) and then 1 or more word (alphanumeric or underscore characters). See how your regex actually performs.

Use the following replacement:

.replace(/\[\[(.*?)]]/g, "$1")

See this demo

The /\[\[(.*?)]]/g will find all non-overlapping occurrences of [[, followed with 0+ characters other than a newline (if you need to also match newlines, replace with [^]*? or [\s\S]*?), and then two literal ] symbols (note that you do not need to escape them outside the character class in JS patterns).

The .*? matches as few any chars other than a newline as possible for the engine to return a valid match, i.e. it matches up to the first occurrence of ]]. If the match must include everything up to the last occurrence of ]], .* is enough.

Note that if the substrings inside [[ / ]] are very long, I'd rather unroll the whole regex pattern as /\[\[([^\]]*(?:](?!])[^\]]*)*)]]/g.

Upvotes: 2

Related Questions