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

Creating a hover effect for a div in jQuery or CSS: Keeping the div visible even when hovered

I have two divs in my layout: one is titled "title" and the other is called "description". I successfully made the description div appear when hovering over the title div. You can see an example of this behavior in action on this fiddle Now, I want to cha ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

My jquery filter is not functioning properly

I need help making the active class work on each category when clicked, shifting to the next one. I've tried implementing it but no luck so far. $(document).ready(function() { $('.list-inline-item').click(function() { const value = ...

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

AngularJS Variable Comparison: A Detailed Analysis

I am currently facing an issue with my custom filter in my code that filters based on gender (male or female). When I click on the male value, female values are also displayed because the female value contains "male" in it. However, when I click on the fem ...

Troubleshooting Issues with ASP.NET MVC5 CRUD Validation Inside Modal

My modal validation is functioning correctly, however, I am experiencing an issue where the form always returns valid()=false resulting in not hitting the Controller Method. I have attempted to use the unobtrusive.parse method for validation and it works ...

I implemented a proxy in my project to handle cross-domain requests, however, the requested address changes when I make a

Unable to Cross Domains http://localhost:8080/api/login has to be redirected to http://localhost:8080/index.html proxyTable: { '/api': { target: 'http://47.106.74.67:8080', changeOrigin: true, pathRewrite: ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

Are there any AJAX tools or packages in Node.js Express for connecting (posting/getting) with other servers and retrieving data?

Can someone please guide me on how to utilize ajax in node.js to send and receive JSON data from another server? Is there a package available that allows for this functionality, similar to jQuery's $.ajax, $.post, or $.get methods? ...

What is the best way to interrupt an animation and restart it?

On my webpage, I have implemented some anchors and links that navigate to these anchors. When I click on a link, the background-color of the anchor changes. I use animation to gradually fade out this color over 10 seconds - starting with white and then rem ...

I am looking to insert an array of a specific type into a Postgres database using Node.js, but I am unsure of the process

query.callfunction('fn_create_mp_product', parameters, (err, result) => { if (err) { console.log(err) callback(err); } else { if (result.status == 'success') { callb ...

Easily transform a CSS file for optimal use on dark backgrounds from scratch

I've got around 200 CSS files that look like this: /** * GeSHi Dynamically Generated Stylesheet * -------------------------------------- * Dynamically generated stylesheet for bnf * CSS class: , CSS id: * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 ...

How to relocate zeros to the end of an array using JavaScript without returning any value?

I'm currently working on a coding challenge from leetcode.com using JavaScript. I'm relatively new to algorithms and seem to be struggling with getting my initial submission accepted. The task at hand is as follows: Given an array nums, the goa ...

Guide to rendering pages in SSR mode in NextJS on a specific environment and serving static pages on a different environment

I am facing a challenge with my setup where I have a Strapi backend deployed on the environment I manage, and a NextJS frontend hosted on Vercel. On the other hand, my client has the same Strapi backend code running on Google Cloud and the frontend code ho ...

Top approach for creating/previewing a website using PHP, CSS, and MYSQL

When creating a website that will eventually be hosted on a remote server, what is the most effective way to code and test? Here are some examples of what I mean: - Develop locally on your computer and access files from there. Should libraries and databa ...

Tips for programmatically adding together numerous input entries within a PHP while loop utilizing java-script on the onfocusout event

Currently, I am working on a method to determine the value of the following id: id="salenag<?php echo $a; ?>". This involves fetching multiple values from a database using PHP and then summing them up before injecting the total into an in ...

Changing Settings on the Fly with JQuery

I am facing an issue with a table that has values generated dynamically using PHP, such as id and name attributes (e.g. id="question_". My challenge is how to set an element attribute considering this dynamic nature. For instance, I need to update the tex ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

Does vuetify have a v-autocomplete callback for when there is no filtered data available?

Is there a method to detect when the v-autocomplete component in Vuetify.js displays "no data available" after filtering? I have searched the events documentation here https://vuetifyjs.com/en/api/v-autocomplete/#events Is there a workaround for this iss ...

Switching the Vue image on Routerlink's isExactActive feature

Is there a way to display different images based on whether a link is active or not? <router-link to="/"> <img src=" :active = isExactActive ? pic_active.png : pic_inactive.png}}" /> //Something along these lines ...