![](/img/trans.png)
[英]Regex - Replace text in HTML string when not contained within HTML tags
[英]Replace color strings in HTML string within tags
我有一個包含 HTML 的字符串。 現在我想用一些東西替換標簽中所有出現的顏色。 我該怎么做呢?
const workInProgressRegex = /<[\w]+[^>]*>.*?(#(?:[0-9a-fA-F]{3}){1,2})<\/[\w]+>/gim;
const exampleString1 = `<div><span class="foo" style="background-color: #ffffff;">#222222 foo #111111 abc #000000</span></div>`;
const exampleString2 = `<div><span class="foo" style="background-color: #ffffff;">"'#222222 foo #111111 abc #000000</span></div>`;
const result1 = exampleString1.replaceAll(workInProgressRegex, "bar");
// should be `<div><span class="foo" style="background-color: #ffffff;">bar foo bar abc bar</span></div>`
const result2 = exampleString1.replaceAll(workInProgressRegex, "bar");
// should be `<div><span class="foo" style="background-color: #ffffff;">"'bar foo bar abc bar</span></div>`
附加信息:我想替換 HTML 標簽內出現的任何十六進制顏色的所有文本。 我給出的例子只是例子,並不詳盡。
雖然我不是在尋找牢不可破的東西,但它應該是堅固的。 這意味着,十六進制代碼可以位於 innerHTML 內的任何位置,它們不必位於末尾或開頭。 標簽中也可以有任意數量的十六進制代碼。
我認為您正在尋找這個正則表達式(#[0-9|af]{6})
,它應該選擇您所有的十六進制顏色代碼。
問題是你不能簡單地替換所有出現的 #xxxxxx 因為這也會刪除style="background-color: #ffffff;"
從您的字符串中,這是您要保留的內容。
然而,您可以做的是鏈接兩個替換函數,其中第一個查找模式#xxxxxx[empty space] ,第二個查找模式#xxxxxx< (因為最后一次出現#000000</span>
將被bar /span>
替換bar /span>
否則)。
const exampleString2 = `<div><span class="foo" style="background-color: #ffffff;">"'#222222 foo #111111 abc #000000</span></div>`; var res = exampleString2.replace(new RegExp(/(#[0-9|af]{6} )/, 'g'), 'bar ').replace(new RegExp(/(#[0-9|af]{6}<)/, 'g'), 'bar<'); console.log(res);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.