views:

53

answers:

3

Here is the format of the css I'm trying to edit using jquery.

/*8d*/ .class{color:#444444;}
/*5d*/ .class{background-color:#444444;}
/*3f*/ .class{color:#444444;}
/*9d*/ .class{color:#444444;}

I want to replace several entire lines within using Regular Expressions. For example, How do I select line 5d the replace with "/*5d*/ .new{border:#676767;}" so the end result is;

/*8d*/ .class{color:#444444;}
/*5d*/ .new{border:#676767;}
/*3f*/ .class{color:#444444;}
/*9d*/ .class{color:#444444;}

Thanks.

+1  A: 

could you use toggleClass or addClass / removeClass?

bluevoodoo1
No ... would've been great if I could though :) ...
Norman
+1  A: 

If you want to replace the 5d line, search for:

\/\*(5d)\*\/.*

and replace the match with

/*\1*/ .new{border:#676767;}

Note that \1 is a backreference to 5d.

Chetan
Works great .. THANK YOU ! :)
Norman
errr .. how do I replace "5d" with a js variable ? sorry, have tried googling :)
Norman
When you set the regex pattern, you would do it like this: `var regex = new RegExp("\/\*(" + yourVar + ")\*\/.*");` ...assuming `yourVar` contains `5d` or the likes.
Chetan
A: 
css.replace(/\/\*5d\*\/.*/, '/*5d*/.new{border:#676767;}');

Of course if you have your css in that format, with one rule on one line. If you have it on multiple line you'll have to use this:

css.replace(/\/\*5d\*\/{.*?}/s, '/*5d*/.new{border:#676767;}');

But if you have comments inside you rule things get more complicated and I don't think regex is enough.

Alin Purcaru
Sadly, REs in most (all?) JS engines don't support look-behind.
outis
I checked the ECMA-262 v5 and it seems that just lookaheads are specified. Thank you for the information.
Alin Purcaru