Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something 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

In this file, I want to highlight a specific portion:

Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and

To achieve this, I receive start and end offsets for the desired string from the backend.

I then utilize the following method to apply the highlighting:

$scope.highlightHTML(responseData, startOffset, endOffset);
$scope.highlightHTML = function(content, startoffset, endoffset) {
  var className = 'mark';
  console.log(content.substring(startoffset, endoffset));
  return content.replace(content.substring(startoffset, endoffset), '<span class="' + className + '">$&</span>');
}

This method replaces the specified text with a span tag. However, when dealing with multiple elements in the array that need highlighting, the offsets need adjustment due to the insertion of span tags.

var length = '<span class="mark"></span>'.length:
jsonDataArray.forEach(function(item, index) {
    responseData = $scope.highlightHTML(responseData, item.startOffset + (index * length), item.endOffset + (index * length));
});

The main issue arises when trying to highlight the text 1500s, as it may be part of a previously highlighted string. This discrepancy leads to incorrect offset calculations and difficulty in locating the exact string for highlighting.

If anyone has a solution to this problem, I would greatly appreciate the assistance.

Answer №1

As mentioned in the comments above, you have the option to create a component that applies different styles to your text. For reference, please take a look at this Plunkr example or visit execCommand link for more features you can incorporate.

For instance:

$window.document.execCommand('foreColor', false,'red');

This will set the color to red on your text.

The convenient part is that you don't need to worry about closing styling tags; everything is handled automatically.

You can star & watch this GitHub repository to stay updated on upcoming features. I've also explained how to bind ng-model with an external component for data extraction purposes.

Ensure that when implementing this feature, you restrict what actions can be taken, as it provides various functionalities (which may not align with your expectations). Use it wisely.

Update

Refer to this file. You can access and download the code from the Git repository.

Answer №2

Why have you chosen to use an offset instead of the length of the string? A more efficient approach is to utilize jquery, which can determine the exact length of the specific text you wish to highlight (particularly useful for dynamic string texts). 1. Begin by locating the first character, then incorporate the string's length. 2. Proceed with highlighting the designated text.

jquery - $('#... span'), ....focus on your element... range.setStart(focused element from prior focus, " + str( result) + ");range.setEnd(end of the focused element," + str(result + len(enter code here name)) + ");sel = window.getSelection();enter code heresel.removeAllRanges();sel.addRange(range);"

You have the liberty to select from any tag without necessitating the addition of span tags or text replacement.

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

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...

The title attribute fails to display the entirety of the content

My div has a title attribute with 4000 characters, but when I hover over it, the full content is not displayed. Is there a way to show the complete text? https://codesandbox.io/s/strange-hugle-mvwu5 ...

Calculate the total number of blank input boxes within a specific row of the table

What is the method to count the number of input boxes without a value in a table row using jquery? For instance: <table id="table1"> <tr class="data" id="row5"> <td><input type="text" value="20%" /></td> <td><input ...

Setting dynamic image dimensions within a div element

Is there a way to display the div width in percentage even when the image is not loaded? The image sizes are mentioned in percentage and they load dynamically, making it impossible to fix their size. How can we ensure that the div maintains the correct wid ...

What are some ways to calculate the average of data values in a Vue v-simple-table?

I am working with a v-simple-table. The "TotalAverage" value represents the total average of "ggFinalgrade". How can I retrieve this value? View current image The image I want to display The initial value is 20 calculated as (30+20+10)/3=20 The seco ...

Styling the scrollbar for the PDF element on an HTML page

I have a div that contains an object "linked" to a .pdf file. Is it possible to customize the scrollbar style using CSS or JavaScript/jQuery? <div id="container"> <object data="document.pdf" type="application/pdf" ...

Checking for identical inputs in a React component's onChange event: how can it be done?

I'm currently working on implementing an onChange event in React to validate if two input fields are identical, specifically for confirming a password. The goal is to display a message below the input fields as users type, indicating whether the passw ...

Implementing setState in React with nested objects and dynamic keys

Here is how my state appears: state = { basic: { entry: 'index.js', output: { path: 'dist', filename: 'bundle.js', } } } An onChange event callback for input has been defined as follows: handleU ...

The Bootstrap toast fails to appear on the screen

I am currently working on a website project using HTML with bootstrap and javascript. I have been attempting to include a toast feature by implementing the code provided on the bootstrap website: <div class="toast" role="alert" aria-live="assertive" ...

Accessing a Child Component Function in Material UI

Utilizing the Material UI framework, I am constructing an application with React. Included in this application is a Dialog feature that permits users to modify various information about an object (referencing the code below). The dialog consists of two but ...

Bullet-point Progress Indicator in Bootstrap

Seeking guidance on how to create a Bootstrap progress bar with dots incorporated, similar to the image linked below. Any tips or resources where I can learn more about this technique? https://i.stack.imgur.com/BF8RH.jpg .progress { width: 278px; he ...

Using the datepicker class in an input field causes issues with the functionality of the bootstrap datepicker, specifically the autoclose, endDate, and startDate properties do not function as

I'm facing an issue with my code when I add the datepicker to the input field's class. JS $(document).ready(function () { $("#ActionDateInput").datepicker({ autoclose: true, endDate: new Date() }); }); HTML <input type= ...

What steps can I take to ensure that this code is validated prior to proceeding to the subsequent page?

I am experiencing an issue with this HTML fieldset form code. When I click the submit button, it redirects to the next page. However, if I remove "next" from the button class, the form validates but does not proceed to the next page. Can you please help me ...

AngularJS toaster doesn't seem to be appearing

I have integrated the angularjs toaster library into my project. Here are the necessary references: https://github.com/jirikavi/AngularJS-Toaster Added the following references for the library: <link rel="stylesheet" href="bower_components/Angu ...

A guide on extracting data from a mongoose model and assigning it to a variable in a manner similar to the MVC design pattern

Below is an example of MVC framework code in PHP. I'm seeking advice on how to implement a similar process in Node.js using Mongoose. I am working with Node.js, MongoDB, and REST API development. Controller file: <?php class Myclass { public fu ...

Navigating from a table row to an individual item within Angular using routing

I am currently working on a page that displays a table of Listings (also known as Products). The task at hand is to include an Edit Listing button in each row which will redirect to a new page for editing a single Listing (Product). Essentially, the flow ...

An alternative to PHP's exec function in Node.js

I am interested in developing a piece of software using C (such as prime number factorization) and hosting it on my web server with Node.js. Following that, I would like to create an HTML document containing a form and a button. Upon clicking the button, ...

No longer able to bind events after making changes to SVG elements [using JSFiddle]

I've coded a personalized directive to display tags like `<rect>` and `<circle>` within `<svg>` elements. My shapes model is simply an array of objects with different attributes such as `width`, `height`, and `stroke-width. These s ...

Header and footer set in place with customizable height paired with a dual-module sidebar

I'm working on a layout that includes a fixed footer and header. My goal is to make the height of the "info-box" div variable, while having the "scrolling-div" fill the remaining vertical space in the right column. The issue arises when setting the he ...

Unable to reset iframe style height in IE8 using JavaScript

I am encountering an issue with resetting the height of an iframe using JavaScript. Here is the code snippet I am working with: var urlpxExt = document.getElementById('urlPx'); urlpxExt.style.height = "200px"; While this approach works well in m ...