Search code examples
javascriptjquerystylingparentheses

How to style parentheses and the text inbetween them?


I have a line of text:

<h1 class="productName">Product Name (Blue)</h1>

and I wish to style the parentheses and the text inbetween - ideally placing a span around them.

I have tried adapting the solution here, but I can't get it to work.


Solution

  • If you have this HTML:

    <div id="test">Product name (colour)</div>
    

    You can use this javscript to add the span as requested:

    var o = document.getElementById("test")
    o.innerHTML = o.innerHTML.replace(/\([^\)]*\)/, '<span class="highlight">$&</span>');
    

    And, then set CSS for the class to control the formatting.

    If you want to replace more than one, then you would have to add the g flag and change the regex slightly for min match instead of max match to this:

    var o = document.getElementById("test")
    o.innerHTML = o.innerHTML.replace(/\([^\)]*?\)/g, '<span class="highlight">$&</span>');.
    

    You can see it work here: http://jsfiddle.net/jfriend00/NyaZ2/.

    OK, now that you've included the HTML, you can do it using jQuery like this:

    var o = $(".productName");
    o.html(o.html().replace(/\([^\)]*?\)/g, '<span class="highlight">$&</span>'));