Using JavaScript to format an array's values within a string in a stylish way

I am facing a challenge in styling words from an array if they are found in a string. My current code is not working as expected.

Below is the code I am using, where I am looping through both the array of words and the table containing strings.

Only one word (venkel) from the array gets picked up and replaced just once in the first string. However, I need all words in the array to be replaced with bold values if found in the strings.

UPDATE: When using Regex, not all words are updated

var productName = ["witte asperges", "crème fraîche", "wijtingfilet", "selder", "BIO wortelen", "BIO rode ui", "venkel"],
  descriptionName = document.getElementsByClassName("Description");
for (var i = 0; i < productName.length; i++) {
  var product = productName[i];
  for (var x = 0; x < descriptionName.length; x++) {
    var description = descriptionName[x];
    if (description.textContent.indexOf(product) !== -1) {
      descriptionName[x].innerHTML = descriptionName[x].textContent.replace(product, product.bold());
    }
  }
}
<table style="width:60%;">
  <tbody>
    <tr>
      <td class="data Description">Spoel ondertussen de wortelen goed schoon en snijd de wortelen en de selder in blokjes van 2 cm. Verwijder het stugge uiteinde van de venkel en snijd in plakjes van 2 cm. Voeg de venkel, de wortelen en de selder toe aan de pan en laat 4 min.</td>
    </tr>
    <tr>
      <td class="data Description">Spoel de aardappelen en boen ze goed schoon. Snijd ze in blokjes van 3 cm en kook ze in zo’n 10-15 min. beetgaar in lichtgezouten water.</td>
    </tr>
    <tr>
      <td class="data Description">Giet de crème fraîche bij het vispannetje, breng op smaak met een snuifje zout en flink wat zwarte peper en laat 3 min. opwarmen. Dien het vispannetje op met de puree. Smakelijk!</td>
    </tr>
  </tbody>
</table>

Answer №1

To perform a global replace using regular expressions on your product variable, you can use the following code:

new RegExp(product,"g");

Make sure to update the code to

descriptionName[x].innerHTML = descriptionName[x].innerHTML.replace(reg, product.bold());
in order to change the HTML content and not just the text content with bold styling.

VIEW THE WORKING EXAMPLE BELOW

var productName = ["witte asperges", "crème fraîche", "wijtingfilet", "selder", "BIO wortelen", "BIO rode ui", "venkel"],
  descriptionName = document.getElementsByClassName("Description");
for (var i = 0; i < productName.length; i++) {
  var product = productName[i];
  for (var x = 0; x < descriptionName.length; x++) {
    var description = descriptionName[x];
    if (description.textContent.indexOf(product) !== -1) {
      var reg = new RegExp(product,"g");
      descriptionName[x].innerHTML = descriptionName[x].innerHTML.replace(reg, product.bold());
    }
  }
}
<table style="width:60%;">
  <tbody>
    <tr>
      <td class="data Description">Meanwhile, rinse the carrots thoroughly and cut them along with the celery into 2 cm cubes. Remove the tough end of the fennel and slice it into 2 cm pieces. Add the fennel, carrots, and celery to the pan and cook for 4 minutes.</td>
    </tr>
    <tr>
      <td class="data Description">Rinse and scrub the potatoes well. Dice them into 3 cm pieces and boil them in lightly salted water until they are tender, about 10-15 minutes.</td>
    </tr>
    <tr>
      <td class="data Description">Add the crème fraîche to the fish stew, season with a pinch of salt and plenty of black pepper, and heat for 3 minutes. Serve the fish stew with the mashed potatoes. Enjoy!</td>
    </tr>
  </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is an encrypted JSON API that utilizes cookies for authentication and nonces considered to be secure in general?

Is it possible to create a secure SSL'ed API that authenticates using a session ID within a cookie, includes a nonce as a query parameter, and always responds with a JSON 'Object' response? How effective would this be against XSRF attacks? ...

Guide on Modifying the color of a selected link tag

Here is the code snippet for a link tab: HTML <div class="sortLinks right"> <label>Sort by</label> <a onclick="javascript:SortOrder('DATE')" href="#">Date Modified</a> <span class="sort_sep">& ...

What causes ngClick to stop working following $compile?

http://plnkr.co/edit/kL2uLPQu2vHHKIvRuLPp?p=preview Upon button click, the controller calls a service to compile HTML and inject it into the body. The compiled HTML (displaying "Hello World" from $scope.name) is referring to the scope of the controller, ...

Issue with merging JSON in Angular using RxJS

Seeking assistance with combining two JSON objects in an Angular application. JSON Object 1: { "level1": { "level2": { "level31": "Text 1", "level32": "Text 2", "leve ...

What is the best way to access a component's value from a different component in Vue script?

I have two Vue components in my PHP file: "application" and "vn" component. I am trying to fetch {{obj.vacancies_left}} from the "vn" component and use it in the "application" component. However, I keep getting an undefined variable error. I attempted to r ...

Avoid running getStaticPaths for a specific locale

Is there a way to prevent Next.js getStaticPaths from generating static pages for a specific locale? In my Next.js configuration: i18n: { locales: ['default', 'en', 'hu', 'de', 'cz', 'eu', ...

What steps can be taken to execute a function when a button remains unclicked?

$("#RunCode").click(function(){ var $this = $(this); if($this.data('clicked')) { console.log("Is clicked"); $(".documentWrite").text("Is clicked"); } else { $this.data('clicked', true); consol ...

Having trouble with TypeScript Library/SDK after installing my custom package, as the types are not being recognized

I have created my own typescript library using the typescript-starter tool found at . Here is how I structured the types folder: https://i.stack.imgur.com/igAuj.png After installing this package, I attempted a function or service call as depicted in the ...

What sets apart the intended usage of the DOM `hidden` from the CSS `visibility` property?

Exploring the DOM property hidden and the CSS property visibility, I find myself unsure of when to utilize each one. What are the distinctions in their intended purposes? While they may serve similar functions, I am curious about the underlying motivation ...

Uploading files with ASP.NET MVC 3 using a JSON model

I am currently working on a web application that communicates with the server-side (ASP.NET MVC 3) by sending JSON data to specific URLs, without the use of HTML forms. Is there a way for me to send a file to the server and associate it with HttpPostedFil ...

using ng-class or ng-style for displaying error messages when validating a text area content

I'm curious about the most effective "angular" method for changing the character count style for validation purposes. I have a text area with a 250-character limit. Instead of restricting users to exactly 250 characters, we want to allow them to excee ...

Ways to store AJAX response data for future use

I am struggling with implementing the getState function. My goal is to update a field on click using a state value retrieved from an AJAX call. I have come across mentions of promises in other responses, but I am unsure how to integrate them into my code ...

Determining the specific page or method being called in a JSP page upon submission

There is a JSP page named X.JSP that contains radio buttons and a submit button. When the submit button is clicked on X.JSP, the next page Y.JSP is displayed with parameters xxxx=1111&yyyy=2222&zzzz=3333. Is there a way to determine the page, ser ...

How can I resize my image to fit the parent div while preserving its aspect ratio?

My image is dynamic, switching between portrait and landscape orientations. I want it to fill its parent div 100% while maintaining its aspect ratio. I've seen similar questions asked, but I have some specific requirements: Avoid using background c ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

How can I stop the body from scrolling to 100% height when the virtual keyboard is displayed?

My chat app has sticky header and footer elements. To handle the mobile virtual keyboard opening, I adjust the document's height using window.visualViewport.height. For example, if the browser's height is 1000px and the virtual keyboard takes up ...

Is there a way to add a price to an object in JavaScript?

Purchasedata.find(function(err, purchasedatas) { if (err) { return handleError(res, err); } var totalprice = 0; for (var i = 0; i < purchasedatas.length; i++) { findProduct(i, function(i, price) { }); } ...

Transforming query language from jQuery to Pure JavaScript

I have the following jQuery code that I am attempting to remove and convert into standard JavaScript: $('.switch').click(()=>{ $([".light [class*='-light']", ".dark [class*='-dark']"]).each((i,ele)=& ...

What is the best way to emphasize a link to the current page in vue.js?

I am working on a sidebar feature that displays several dynamically generated links (similar to creating notes and then linking to them): https://i.stack.imgur.com/1lxcy.png Users can add a new note by clicking the 'Add stage' button. The list ...

Verifying user authorization for Microphone access prior to triggering event in React application

I have created a React component featuring a microphone button that operates as follows: OnMouseDown => Initiates audio recording by the user OnMouseUp => Ceases audio recording To elaborate, while the button is pressed down, the user can continue ...