简体   繁体   中英

JavaScript/JQuery string replace

I have the following string which is a CSS selector:

#downloads > ul > li:nth-of-type(1) > ul > li:nth-of-type(3) > a

This CSS selector works fine in FireFox, CHrome and Safari but IE 6 does not support the nth-of-type selector. The CSS selectors I am working with are generated by Nokogiri and I can not change them.

Threw testing I have got the following working:

#downloads > ul > li:nth(0) > ul > li:nth(2) > a

Changing the nth selector to a plain nth and subtracting one from the nth value. I have been trying to programmitcally with JS to convert a CSS selector from using nth-of-type to normal nth? So after running it threw:

#downloads > ul > li:nth-of-type(1) > ul > li:nth-of-type(3) > a

Would become

#downloads > ul > li:nth(0) > ul > li:nth(2) > a

Cheers

Eef

Javascript

var str = "#downloads > ul > li:nth-of-type(1) > ul > li:nth-of-type(3) > a";
str = str.replace(/:nth-of-type\(([0-9]+)\)/g, function(match, first) {
   return ":nth(" + (parseInt(first)-1) + ")";
});

alert(str); // -> #downloads > ul > li:nth(0) > ul > li:nth(2) > a

[ See it in action ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM