亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何排除正則表達式字符串中的類?

如何排除正則表達式字符串中的類?

紅顏莎娜 2022-05-26 15:38:10
我目前正在嘗試構建一個正則表達式,它替換字符串中的所有 HTML 標記,不包括特殊元素。問題是我發現沒有辦法排除特殊元素的結束標記。這是我的代碼:let str = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';console.log(str.replace(/(?!<div class="keep-this">)(<\/?[^>]+(>|$))/g, ""));
查看完整描述

2 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

試試這個選項,它匹配所有的 HTML 標簽,不包括那些有屬性的標簽class="keep-this"。


let str = 'You have to pay <input class="some-class"/> blah <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';


console.log(str.replace(/<\s*([^\s>]+)(?:(?!\bclass="keep-this")[^>])*>(.*?)(?:<\/\1>)|<\s*([^\s>]+)(?:(?!\bclass="keep-this")[^>])*\/>/g, "$2"));


以下是正則表達式模式的解釋:


<                                 match < of an opening tag

\s*                               optional whitespace

([^\s>]+)                         match and capture the HTML tag name in $1 (\1)

(?:(?!\bclass="keep-this")[^>])*  match remainder of tag,

                                  so long as class="keep-this" is not seen

>                                 match > of an opening tag

(.*?)                             match and capture the tag's content in $2,

                                  until hitting the nearest

(?:<\/\1>)                        closing tag, which matches the opening one

|                                 OR

<\s*([^\s>]+)                     match a standalone tag e.g. <input/>

(?:(?!\bclass="keep-this")[^>])*  without a closing tag

\/>                               which matches                            

然后,我們只需將所有此類匹配項替換為空字符串,即可有效地刪除它們。


查看完整回答
反對 回復 2022-05-26
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

如果你想刪除所有沒有類的 html 元素,keep-this你也可以使用DOMParser,例如使用:not。


let str = 'You have to pay <div class="keep-this">$200</div> per <span class="date">month</span> for your <span class="vehicle">car</span> <div class="keep-this">$500</div> also';

let parser = new DOMParser();

let doc = parser.parseFromString(str, "text/html");

doc.querySelectorAll("body *:not(.keep-this)").forEach(e => e.replaceWith(e.innerHTML));

console.log(doc.body.innerHTML);


查看完整回答
反對 回復 2022-05-26
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號