Guide to emphasizing a specific term within a string by utilizing coordinates in javascript

I am facing a challenge when trying to highlight multiple words within a sentence. Specifically, I have text data that looks like this:

"The furnishing of Ci Suo 's home astonished the visitors: a home of 5 earthen and wooden structures, it has a sitting room with two layers of glass as well as a warehouse filled with mutton and ghee ."

Along with an array of objects:

entities: [
      {
        "entity_type": "PERSON",
        "index": [
          18,
          26
        ],
        "namedEntity": "Ci Suo 's"
      },
      {
        "entity_type": "CARDINAL",
        "index": [
          69,
          69
        ],
        "namedEntity": "5"
      },
      {
        "entity_type": "CARDINAL",
        "index": [
          130,
          132
        ],
        "namedEntity": "two"
      }
    ]

My goal is to format it in the following way: https://i.sstatic.net/QW41M.png

Here's what I've attempted so far:

const find = entities; // word to highlight
let str = text; // contain the text i want  to highlight

for (let i = 0; i < find.length; i++) {
  str = str.replace(new RegExp(find[i], "g"), match => {
    const color = randomColor();
    return `<span style="background: ${color}">${match}</span>`;
  });
}

However, this approach has led to some issues such as

  • the later tags can be matched in the next iteration if I have a word like "an"
  • two same words get the same label

If you have any alternative methods or suggestions that could help, I would greatly appreciate it. Thank you!

Answer №1

Adding word-boundaries like \b can be very helpful to find specific words in a text, as @Phill mentioned earlier. Give this a try:

for(let i = 0; i < find.length; i++) {
   const regExp = new RegExp("\\b" + find[i].namedEntity + "\\b","g");
   str = str.replace(regExp, function (match, index, wholeStr) {
        const color = randomColor();
        return `<span style="background: ${color}">${match}</span>`;
    });
}

Answer №2

It seems like all the necessary information is available in your entities array to update the original text. You can achieve this using the code snippet below.

var text = "The furnishing of Ci Suo 's home astonished the visitors : a home of 5 earthen and wooden structures , it has a sitting room with two layers of glass as well as a warehouse filled with mutton and ghee ."
var entities = [
      {
        "entity_type": "PERSON",
        "index": [
          18,
          26
        ],
        "namedEntity": "Ci Suo 's"
      },
      {
        "entity_type": "CARDINAL",
        "index": [
          69,
          69
        ],
        "namedEntity": "5"
      },
      {
        "entity_type": "CARDINAL",
        "index": [
          130,
          132
        ],
        "namedEntity": "two"
      }
    ]


function buildText(text, entities) {
  var newText = text;
  
  entities.forEach(({entity_type, namedEntity, index}) => {
    newText = newText.replace(namedEntity, `<span class=${entity_type.toLowerCase()}>${namedEntity}</span>`)
  } )
  
  return newText;
}

document.getElementById('content').innerHTML = buildText(text, entities);
.person {
  background-color: red;
}

.cardinal {
  background: cyan;
}
<div id='content' />

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

Div positioned absolutely beneath the footer

I'm facing an issue where the footer field I add under a div with an absolute value escapes on both mobile and desktop. Additionally, the iframe does not have full height. Any suggestions on what I should do? All the specifics are provided in the att ...

Troubles emerge when incorporating the AOS library into main.js in Vue 3

Hey there! I'm currently incorporating the Aos library into my Vue 3 project and encountering issues. import App from './App.vue' import AOS from 'aos' import 'aos/dist/aos.css' import { createApp } from "vue" ...

Tips for changing the focus between various modals and HTML pages after minimizing a modal with jQuery

I have been utilizing a plugin from to minimize a bootstrap modal within my angular application. The problem I am facing with this plugin is that whenever I minimize a modal, I am unable to interact with the html page, such as typing in input boxes or sc ...

Oops! Make sure to call google.charts.load before calling google.charts.setOnLoadCallback to avoid this error

My HTML file includes the following imports: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ...

How to dynamically add variables to object paths using JavaScript and Angular

I've been struggling to grasp this concept, despite hours of searching. My goal is to dynamically generate form fields based on a user-selected 'type' from a dropdown menu. This will be linked to the variable "currentType" in Angular, which ...

Google API integration in Chrome Extension Manifest

I'm seeking advice on how to modify my chrome manifest for an extension in order to enable communication between Google API servers and the application. The application functions properly when accessed directly (not as an extension). However, when lo ...

Is it considered inefficient to import every single one of my web components using separate <script> tags?

Currently, I am in the process of developing a website with Express + EJS where server-side rendering is crucial. To achieve this, I am utilizing web components without shadow dom. Each page type (home, post, page) has its own EJS view. For instance, when ...

Place attribute value directly under the border of an HTML element using a combination of JavaScript and CSS

I'm currently working on a JavaScript script to scan the DOM for elements that have a specific custom attribute called example-type. The goal is to apply CSS styling to draw a border around these elements and then display the value of the example-type ...

Combining multiple meteor servers into a single database collection (local)

I'm currently working on a Meteor project that involves making multiple external API calls at different intervals and storing the retrieved data in MongoDB. My goal is to separate these API calls into individual "micro-services", each running on its ...

Retrieve various URLs within an object using React

My task involves extracting all URLs from a specific object. Object { "Info": "/api/2", "Logo": "/api/2/Logo", "Photo": "/api/2/photo", } I aim to store the responses in a state, ensuring t ...

Tips for preventing PyCharm from automatically completing HTML and Django template tags

While working on Django templates in PyCharm, I noticed that it automatically closes the tags. This can be helpful when starting a new tag, but it becomes annoying when I want to place existing content within a different tag because I have to delete or mov ...

Guide for executing Java code and displaying HTML form fields concurrently in JSP

I have created a JSP page with form fields and Java code in scriptlets. I have imported the Java code into the JSP page and created an object to call the functions of that Java class. When I run the JSP, the page remains blank until all the Java code has ...

When a table undergoes a dynamic reload, the formatting for the columns fails to display properly

After fetching image metadata from an API call, a table is dynamically generated on page load. Subsequently, when new images are uploaded, the function responsible for building the table is called again to include this new data. However, despite the CSS st ...

Ensure that both Vue methods are executed synchronously

I am working with two Vue methods: (1) this.retrieveSavedSearches() (2) this.updateDefaultSelectOption() Is there a way to ensure that method (2) only executes after method(1) has completed its execution? ...

creating unique icons in primefaces

I attempted to create a new icon for my p:commandButton, but unfortunately, I was unsuccessful. I followed the method outlined in this helpful link: PrimeFaces: how can I make use of customized icons? However, this approach did not work for me. Below i ...

Is it possible to use jQuery to load content and notify the calling window?

I am implementing the JQuery event "load" to detect when the full HTML window has finished loading along with all scripts being executed. I know this function is typically used within the document.ready event. However, my scenario involves a parent window ...

Deactivate Search Functionality for Users who are not Logged in on an Angular 2 Application

The login component and view are functioning as intended, preventing users from accessing AuthGuard protected routes if they're not logged in. However, I'm facing a challenge with the search bar displayed on the home login screen (actually presen ...

Why is the code able to execute following the setState hook without any listener declared in the useEffect hook?

Recently, I came across an expo barcode scanner example where a function is executed after a setState hook. This puzzled me as I thought that calling the setState hook would trigger a re-render of the component. Can anyone explain why the function runs aft ...

Web performance issues noticed with Angular 8 and Webpack 3.7 rendering speed

My web application is currently taking 35 seconds to render or at least 1.15 seconds from the initial Webpack start. I've made efforts to optimize Webpack, which has improved the launch speed, but the majority of time is consumed after loading main.j ...

Mastering the use of node cluster mode in conjunction with agenda cronjobs

Currently, I am utilizing nodejs and agenda to run cronjobs. With a total of 10 cronjobs in place, the process is taking longer as nodejs is single-threaded and they all run simultaneously. In an attempt to resolve this issue, I experimented with pm2 by e ...