Implementing various distinct string substitutions based on the specified character beginning and end positions

I have a string of text:

Google is a search engine created by Larry Page and Sergey Brin.

Within this string, there are certain named entities stored in a nested array. Here's what the array looks like:

[["Google","ORG",0,5],["search engine","PRODUCT",12,24],["Larry Page","PERSON",37,46],["Sergey Brin","PERSON",52,62]]

My objective is to replace each occurrence of a named entity with an html element. For example, replacing the word Google would result in:

`<div class="ner-tag">${named_entity[i][0]} <span class="ner-tag-type">${named_entity[i][1]}</span></div>`

The challenge lies in managing the character positions accurately while doing these replacements. Additionally, handling scenarios where similar entities such as Google and Google Docs exist requires more complex processing than a simple global replace operation.

Looking for any helpful insights or tips on how to approach this task effectively.

Answer №1

To achieve this task, one way is to arrange the array containing replacement information in descending order based on their respective indexes. Here's an illustration:

const str = 'Google is a search engine created by Larry Page and Sergey Brin.';
const replacements = [["Google","ORG",0,5],["search engine","PRODUCT",12,24],["Larry Page","PERSON",37,46],["Sergey Brin","PERSON",52,62]];

replacements.sort((a, b) => b[2] - a[2]);

const result = replacements.reduce((a, replacement) => {
  return a.substring(0, replacement[2]) + replacement[1] + a.substring(replacement[3] + 1)
}, str);


console.log(result);

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

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

What could be causing the discrepancy in results between the first and second methods?

Implementing Weather Icons: const getWeatherIcon = (iconParameter) => { const icon = `https://openweathermap.org/img/wn/${iconParameter}@2x.png` return <img src={icon} alt={iconParameter} /> } <div className="weathericon"> ...

The FindProxyForURL function in a pac (proxy-auto-config) file is not compatible with the IE browser

After struggling for three days, we are still unable to solve a peculiar technical issue and now seek your assistance. The PAC (Proxy Auto-Config) file we have created works flawlessly in all browsers except for Internet Explorer (IE). The URL in questio ...

Transforming class components to utilize hooks (storing state within an if statement)

I am facing a challenge with some old code that is structured within a class and I need to convert it to hooks. I have successfully converted most of the code, except for one instance where state is declared inside an if statement. The other conversions in ...

JavaScript and PHP/HTML template engine technology

I've recently discovered the jQuery template engine and am intrigued by its potential. It seems to be very efficient for ajax calls, as the data exchange is minimized. However, when I initially load my application using only PHP and HTML to display ...

"Challenges encountered when using map function to dynamically fill select dropdowns in React with Material UI

I am currently working on populating Material's UI with a list of countries using the following code: import React from "react"; import FormControl from "@material-ui/core/FormControl"; import InputLabel from "@material-ui/core/InputLabel"; import Se ...

Is there a way to make an input field mandatory in Gravity Forms by utilizing javascript or jquery?

I am currently in the process of developing a registration form for an upcoming event using gravity forms. The objective is to allow users to register only if the number of participants matches the number of available shirts. In case they do not match, the ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Is there a way to retrieve the JavaScript Console response code using Python and Selenium's execute_script method?

I am running a JavaScript fetch request in the Chrome developer console using Selenium's execute_script() function. The request performs as expected, but I want to set up a function that can verify if the response is a 403 status code. Is there any Se ...

Ensure that the HTML input only accepts numbers and email addresses

Is there a way to restrict an HTML input field to only accept numbers and email IDs? <input id="input" type="text" /> ...

Utilize an iframe input field to initiate a Jquery event

Thanks to this amazing platform, I was able to discover a solution for expanding an iframe upon clicking using HTML and Jquery. However, my issue remains unresolved. I have successfully expanded the iframe with text, but I want to use input fields within ...

Avoid typing the URL directly into the address bar to prevent redirection

For instance, if I have a domain (abc.com) with a page abc.com/data-list, how can I prevent users from manually typing in the address bar to access that page? I want to use JavaScript to dynamically update the content section without refreshing the entire ...

Vue.js's @click feature can be enhanced with ternary operations

I've been attempting to achieve the following in Vue.js, but I keep encountering an error that says [plugin:vite:vue] Unexpected token (1:27): @click="selectedFiles.push(file.id); selectedFiles.length < 1 ? isCollapse=false: isCollapse=true&q ...

JavaScript object created by splitting a string

I was presented with the following string: result:tie,player:paper,computer:paper One way to handle this could be splitting it into arrays, creating an object, and parsing it. However, this approach may not be ideal. Is there a better method to convert t ...

Including a cancel button to close the open window

var messagebox = Ext.widget("messagebox", { target: grid, progressMessage: "Loading" }); The message box displayed above indicates the loading progress bar that appears when the download button is clicked. I am looking to incorporate a cancel button i ...

A JavaScript alert function that triggers no matter the return value

An alert is being sent by a function when a radio box's value returns as null, even though it should have a value that is not null. The issue lies in another function on the page that hides the tables where these radios are located, making it difficul ...

Exploring the differences in performance between React hooks and React classes

Currently, I am delving into understanding React hooks and could use some assistance with comprehending whether every time a React function renders, the hook state resets. Below is a brief example related to fixing a header on scroll: class Header extends ...

"Showcasing MongoDB information on a webpage using Node.js and HTML

We have stored worker information in MongoDB. Now, how can we display that information on an HTML home page? Here is the code I used to save the data: //routes.js var Employee = require('../app/models/employee'); app.post("/addEmployee", (req ...

Having trouble with the Express.js app.post request functionality

I'm facing a challenge with the Express.js library. I've been attempting to set up a basic post request with the route. I have body-parser installed and am using it for the post data. If I specifically include app.post, it doesn't work, ...

Whenever I launch my React web application, I consistently encounter a white screen when attempting to access it on my phone

After developing my web app in ReactJS and deploying it to the server, I've noticed that sometimes the screen appears white for the first time after deployment. However, when I reload the page, the app runs normally. I am hosting the backend and front ...