Regular cut BBCode
I need a regex to strip any BBCode in a string. I have the following (and an array with tags):
new RegExp('\\[' + tags[index] + '](.*?)\\[/' + tags[index] + ']');
It selects [tag] this [/ tag] just fine, but doesn't work when using [url = http://google.com] this [/ url] .
What do I need to change? Many thanks.
You must allow any character other than ']' after the tag until you find ']'.
new RegExp('\\[' + tags[index] + '[^]]*](.*?)\\[/' + tags[index] + ']');
You can simplify this to the following expression.
\[[^]]*]([^[]*)\[\\[^]]*]
The problem is that it will fit [WrongTag]stuff[\WrongTag]
. Matching nested tags requires multiple use of the expression.
a source to share
You can check balanced tags with a backlink:
new RegExp('\\[(' + tags.Join('|') + ')[^]]*](.*?)\\[/\\1]');
The real problem is that you cannot match arbitrary nested tags in a regex (this is the limit of the regex). Some languages allow recursive regular expressions, but these are extensions (which technically make them irregular, but don't change the name most people use for objects).
If you don't like balanced tags, you can simply remove any tag you find:
new RegExp('\\[/?(?:' + tags.Join('|') + ')[^]]*]');
a source to share
I stumbled upon this thread and found it helpful to help me on the right track, but here I ended up spending two hours building (this is my first RegEx!) For JavaScript and tested it working very well for crazy nests and even incorrectly nested strings. it just works !:
string = string.replace(/\[\/?(?:b|i|u|url|quote|code|img|color|size)*?.*?\]/img, '');
If line = "[b] [color = blue] [url = www.google.com] Google [/ url] [/ color] [/ b]", then the new line will be "Google". Amazing.
Hope someone finds this useful, it was the best match for "JavaScript RegEx strip BBCode" on Google;)
I had a similar problem - in PHP not Javascript - I had to strip the BBCode [quote] tags as well as the quotes in the tags. Added a problem that there is often arbitrary additional material in the [quote] tag, eg.[quote:7e3af94210="username"]
This worked for me:
$post = preg_replace('/[\r\n]+/', "\n", $post);
$post = preg_replace('/\[\s*quote.*\][^[]*\[\s*\/quote.*\]/im', '', $post);
$post = trim($post);
lines 1 and 3 are only intended to strip out any extra newlines and any remaining from the regex.
a source to share