[英]Issue with `` within .replace() tags
如何編輯我當前的代碼以在替換中使用``
。 截至目前,因為它在一個循環內.each
它會找到正確的單詞,然后在該單詞周圍添加<span></span>
6 次。 我希望它只添加一次,所以我讀到你可以使用/g
,但是使用``
我認為是導致我的問題,但我不知道如何合並兩者?
這是我的 JS:
$("#pstad-descrptn-mirror div").each(function () {
let get_pstad_desc_div = $(this).text();
let get_pstad_desc_STORE = get_pstad_desc_div
.split(", and comes with")[0]
.split("located in ")[1];
$(this).html(function () {
return $(this)
.html()
.replace(
`/(${get_pstad_desc_STORE})/g`,
`<span>${get_pstad_desc_STORE}</span>`
);
});
})
我對 javascript 或 jquery 解決方案持開放態度。
非常感謝😁
我猜你的HTML看起來像這樣......
<div id="pstad-descrptn-mirror">
<div>
<div>
<div>
Take-away located in Brisbane, and comes with free chips
</div>
</div>
</div>
<div>
<!-- and so on -->
</div>
</div>
您當前查詢的問題在於它找到了作為 ID 容器子級的所有<div>
元素。
您可以使用子組合選擇器運算符僅檢索直接<div>
子級並對其內容進行操作。
您還可以使用正則表達式更輕松地提取您的商店字符串。
document.querySelectorAll("#pstad-descrptn-mirror > div").forEach((el) => {
const store = el.textContent.match(/located in (.+?), and comes with/)?.[1];
el.innerHTML = el.innerHTML.replaceAll(store, `<span>${store}</span>`);
});
document.querySelectorAll("#pstad-descrptn-mirror > div").forEach((el) => { const store = el.textContent.match(/located in (.+?), and comes with/)?.[1]; el.innerHTML = el.innerHTML.replaceAll(store, `<span>${store}</span>`); });
#pstad-descrptn-mirror span { font-weight: bold; }
<div id="pstad-descrptn-mirror"> <div> <div> <div> <p>Take-away located in Brisbane, and comes with free chips.</p> <p>Located in Brisbane, QLD</p> </div> </div> </div> <div> <p>No matches in this div, nothing will be replaced</p> </div> <div> <!-- and so on --> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.