I have HTML like this example:
<div class="code">
function something(a, b)
{
return 0;
}
</div>
I want to surround all parentheses, brackets and braces with a span of class brackets. Like this:
<div class="code">
function something<span class="brackets">(a, b<span class="brackets">)</span>
<span class="brackets">{</span>
return 0;
<span class="brackets">}</span>
</div>
My JavaScript/jQuery so far:
$('.code').each(function() {
$(this).html(
$(this).html().replace("???", '<span class="brackets">$1</span>')
);
});
I really don’t know what to put in place of ???. Anything I can find on the internet is people wanting to match between brackets not the actual brackets themselves.
Just to be clear I want to replace all instances of (, ), {, }, [ and ].
Any help would be hugely appreciated.
You can just stuff them all into a character class (which matches any single character inside the class). The character class itself is denoted by square brackets, so you will have to escape the ones inside (that is only partially true, but it’s definitely good practice):
The outer round parentheses are there so that the captured value actually ends up as
$1. Thegis there so that all occurrences are replaced.Note that this is not a string! Do not surround this with
". Simply supply it as the first argument toreplaceas it is:By the way, you should probably iterate over all text nodes in the DOM and apply the replacement only to those. Otherwise you might add in that tag into attribute values or comments (or worse, embedded JavaScript or CSS).