繁体   English   中英

.replace() 标记中的 `` 问题

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM