The offsets for selecting text are not accurate when multiple values share the same text

I am faced with a text that goes like this ->

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

My goal now is to emphasize a specific part of this text, so I need to determine the start and end offsets of the string.

Let's say

it to make a 

This is the portion of the text I wish to highlight, thus needing the offset of this particular section; my attempt at achieving this involved the following approach:

var startoffset  = $scope.original_doc_content.indexOf("it to make a ");
    var endoffset =  startoffset + string.length;

The issue arises if it to make a appears twice within the given text: in such cases, when I aim to highlight or select the second occurrence, the logic gives me the offset of the first one instead of the desired second one. How can I go about resolving this dilemma?

Answer №1

You can easily enhance your text highlighting using a simple replacement method.

window.onload = function(){
  var str = document.getElementById("mypar").innerText;
  var res = str.replace(/text/g, "<span class=\"highlight\">text</span>");
  document.getElementById("mypar").innerHTML = res;
};
.highlight {
  background-color: yellow;
}
<p id="mypar">This is my text where i want to highlight text or something</p>

Another approach to achieve text highlighting is by getting the index positions of the words. Although not the most efficient solution, this code snippet iterates over the text and logs the index values to the console.

window.onload = function(){
  var str = document.getElementById("mypar").innerText;
  var indexFirstChar = 0;
  var indexOfLastChar = 0;
  var searchString = "text";
  while(str.indexOf(searchString, indexFirstChar + 1) >= 0) {
     indexFirstChar = str.indexOf(searchString, indexFirstChar + 1);
     indexOfLastChar = indexFirstChar + searchString.length - 1;
     console.log(indexFirstChar);
     console.log(indexOfLastChar);
  }
};
<p id="mypar">This is my text where i want to highlight text or something</p>

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

What is the best way to add a bootstrap element to each of the children?

Is there a way to apply the class "bg-dark" to all child elements in this code snippet? <div class="bg-dark"> <div class="row mt-5"> </div> <div class="row mt-5"> </div> <div ...

Is it really impossible to post complex JSON parameters with Restangular?

Is it possible to send a complex JSON object to a PUT route using Restangular? Restangular.one('model3ds', model.uuid).put( api_key: "blabla" model3d: { is_public: true } ) However, the data sent by Restangular appears as: ...

Serve JavaScript files with Express only if the user is authenticated

Within my client-side JavaScript code, I make a request for private content only if the user is authorized using Firebase authentication. Here's an example of how it's implemented: firebase.auth().onAuthStateChanged(user => { if (!user) { ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

Learn how to retrieve data from a dynamically populated drop-down menu when a button is clicked using PHP

I am having trouble retrieving the value from a dropdown menu. The dropdown is populated dynamically from an SQL Server database. Dropdown 1 displays product names and is filled dynamically. Dropdown 2 displays environment names and is filled using HTML. ...

Using PHP to present information in a grid format using customizable templates

My goal is to showcase all the information stored in the database using a grid view based on specific templates. However, I am encountering difficulties in formatting it the way I envision it: [image] [image] [image] [image] [image] [image] [image] [imag ...

Dragging and arranging elements outside the main container is possible with drag-and

Imagine we have a div grid for an inventory that is 128x512px. I am looking to make all the (item 64x64px) divs draggable so they can be snapped onto the grid by dragging them. Inside the inventory, the divs must also be sortable without the use of lists ...

How to effortlessly apply a background image to an SVG path element without any tiling or scaling involved

I am looking to implement a solution similar to the one discussed in Fill SVG path element with a background-image, but with a slight variation. Rather than tiling the image to fill the entire background area, I want the image to be centered within the pat ...

I am experiencing an issue with my images not loading properly upon initial loading in Safari, while all other browsers are working perfectly. What

Currently, I am utilizing the 3D card-flip method on my website and it is functioning flawlessly in Firefox, IE, and even the downgraded versions of IE for older browsers. However, I have encountered an issue with Apple iOS devices and Safari. It appears ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

The UI-router activates the child state prior to resolving the parent state

Currently, I am encountering an issue with executing initialization code within a parent state of the Angular ui-router. The initialization code in question is orderService.getStoreInfo(), which returns a promise. My intention is to trigger the child state ...

Sharing state between child and parent components in React.js functional components

I'm trying to figure out how to pass the Child component's state to the parent component's state. I was able to do this in a class-based component, but now that I'm using a functional component, it's not working anymore. Here is m ...

Creating conditional v-models for checkboxes in Nuxt using API responses

In my Nuxt 2 project with Nuxt 2 Composition API, I am facing an issue related to displaying items that a user can purchase. Specifically, when a user has previously purchased an item, that item should appear disabled and the checkbox should be checked by ...

Is it possible to utilize Bootstrap plugins in conjunction with Angular-UI Bootstrap?

Exploring the possibility of incorporating Angular UI Bootstrap into my upcoming project. Along with this, I am interested in utilizing various standard Bootstrap plugins that are not specific to Angular. Can "vanilla" Bootstrap plugins seamlessly integra ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

Utilizing Azure SDK to send an email

In my Node.js project, I am currently utilizing azure-graph: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId, { tokenAudience: 'graph' } ...

Achieving a consistent border-radius effect during hover transitions

I designed a div that initially displays an image, but upon hovering over it, a second div with text and a solid colored background appears to mask the original content. To see what I'm talking about, check out my jsfiddle: 'Mask on Hover' ...

What is the most effective way to identify mobile browsers using javascript/jquery?

As I develop a website, I am incorporating image preloading using JavaScript. However, I want to ensure that the preload_images() function is not called for users on slow bandwidth connections. In my experience, the main demographic with slow internet spe ...

Performing real-time calculations for standard deviation

I am working with a set of HTML input fields labeled "textfield". I would like to calculate the standard deviation dynamically and display it in another HTML input field. Here is the JavaScript code I am using for the calculation: <script type=&quo ...

Sending files and attributes to a controller in ASP.NET MVC in order to retrieve a dynamically generated PDF as a Binary response - here's how!

I've been struggling with this issue for a few days now and I just can't seem to figure it out. The task at hand is to call an action that requires two pictures and three strings as parameters. This function will use iTextSharp to generate a PDF ...