[英]Issue with `` within .replace() tags
How can I edit my current code to work with ``
within replace.如何编辑我当前的代码以在替换中使用
``
。 As of current because it's inside a loop .each
it will find the correct word but then add <span></span>
around that word like 6 times.截至目前,因为它在一个循环内
.each
它会找到正确的单词,然后在该单词周围添加<span></span>
6 次。 I want it to only add it once , so I read you can use /g
for that, however using ``
I think is causing my issue, however I don't know how to incorporate both?我希望它只添加一次,所以我读到你可以使用
/g
,但是使用``
我认为是导致我的问题,但我不知道如何合并两者?
Here is my JS:这是我的 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>`
);
});
})
I'm open to a javascript or jquery solution.我对 javascript 或 jquery 解决方案持开放态度。
Many thanks 😁非常感谢😁
I'm guessing that your HTML looks something like this...我猜你的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>
The problem with your current query is that it finds all the <div>
elements that are children of the ID'd container.您当前查询的问题在于它找到了作为 ID 容器子级的所有
<div>
元素。
You can use the child combinator selector operator to only retrieve the immediate <div>
children and operate on their content.您可以使用子组合选择器运算符仅检索直接
<div>
子级并对其内容进行操作。
You can also use a regular expression to more easily extract your store string.您还可以使用正则表达式更轻松地提取您的商店字符串。
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.