Converting text in parenthesis to supertext regular expressions

I would like to search text in a div and put numbers in parenthesis in supertext.

So (1) would change to <sup>(1)</sup> but (xyz) would be left untouched.
I would also like to include commas in the supertext.
So (5),(8) would be converted to <sup>(5),(8)</sup>

Does anyone know how to do this?

Thank You E


You can do it like this:

var p = document.querySelectorAll("p"),
    myRegex = /(\\((\\d+)\\))/g;

for(var i=0; i < p.length; i++){
    p[i].innerHTML = p[i].innerHTML.replace(myRegex, function(match) { return "<sup>" + match + "</sup>"; });


Thank you! Is there any way to include a comma in between the parenthesis. IE: (1),(2)?

So you want:

(1) foo bar (2) foo bar (3) foo bar

to become:

<sup>(1)</sup> foo bar, <sup>(2)</sup> foo bar, <sup>(3)</sup> foo bar

Is that correct?

That would work, but actually only a comma would be safer. It would be less likely to trigger false responses.

Thank you!!!


Then I have misunderstood what you are aiming for.
Could you give an example of normal text, then of what you would like it to become (as I do above).

This is one I’m looking for:

 Foo Bar (1) ,(2),(3) Foo Bar (1),(2) 


 Foo Bar <sup>(1) ,(2),(3)</sup> Foo Bar <sup>(1),(2)</sup>

Thank you!!!


Getting complicated. :slight_smile:

This should work:


Looks messy though, it could probably be solved more elegantly.

myRegex = /(\\((\\d+)\\))((\\s*,\\s*)?\\((\\d+)\\))*/g;

I would do it like this:

<p>Foo Bar (1) ,(2),(3) Foo Bar (1),(2)</p>

var p = document.querySelectorAll("p"),
    myRegexp = /\\([()0-9 ,]\\)/g;

for(var i=0; i < p.length; i++){
    p[i].innerHTML = p[i].innerHTML.replace(myRegexp, function(match) { return "<sup>" + match + "</sup>"; });


That does each (#) set individually and misses the comma.


Oh yeah, well spotted.
The regex should be:

myRegexp = /\\([()0-9 ,]\\+)/g;

I forgot the plus to make it greedy.


Thanks guys!!!

One of these days I will master these regular expressions too.


It worked! I just tried it out.