鍍金池/ 問(wèn)答/HTML/ 用正則比較兩個(gè)不同的字符串

用正則比較兩個(gè)不同的字符串

const selector1="html>body>div.container>ul>li.item:nth-of-type(1)>a.active:nth-of-type(3)";
const selector2="html>body>div.container>ul>li.item:nth-of-type(2)>a:nth-of-type(3)"

我想把上面兩個(gè)selector合成一個(gè),如下結(jié)果

"html>body>div.container>ul>li.item>a:nth-of-type(3)"

主要思路是當(dāng)比較到nth-of-type 或 class不同時(shí),直接去掉

回答
編輯回答
放開她

不知道你為什么要這樣做,只能說(shuō)個(gè)我認(rèn)為符合題意的答案


主要思路是當(dāng)比較到nth-of-type 或 class不同時(shí),直接去掉

// 首先將字符串按照>符合切割
const selector1="html>body>div.container>ul>li.item:nth-of-type(1)>a.active:nth-of-type(3)";
const selector2="html>body>div.container>ul>li.item:nth-of-type(2)>a:nth-of-type(3)"
const arr1 = selector1.split(/\s*\>\s*/);
const arr2 = selector2.split(/\s*\>\s*/);
// 假設(shè)分割后得到的數(shù)組長(zhǎng)度是一樣的
const text = arr1.map((item, index)=> {
    if(arr2[index]!==item){
        const child1 = item.split(/[\.\:]/);
        const child2 = arr2[index].split(/[\.\:]/);
        return child1.filter((item)=> child2.includes(item)).reduce((a, b)=> {
            if(b.startsWith('nth-of-type')){
                return a+':'+b;
            }else{
                return a+'.'+b;
            }
        })
    }else{
        return item;
    }
}).join('>');
console.log(text)

純粹只是看到別人,遇到問(wèn)題就想到用正則可以解決,很不爽,強(qiáng)答一波.瞎寫的,懶的寫注釋,我自己都看不懂

2017年7月20日 03:11