简体   繁体   中英

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. 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?

Here is my 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.

Many thanks 😁

I'm guessing that your HTML looks something like this...

<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.

You can use the child combinator selector operator to only retrieve the immediate <div> children and operate on their content.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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