Adjusting the color of a specific part of a text within a string using

I am trying to update the color of specific keywords within a post.

For example:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor lacinia urna eget gravida. Quisque magna nulla, fermentum fermentum od
#keyword1 #keyword2 #keyword3 #keyword4 #keyword5

If the above example is the content of the post, I want to change the styling of the keywords using Next.js.

function applyStylingToKeywords() {
    var startIndices = [];
    var endIndices = [];

    for (let i = 0; i < post.body.length; i++) {
        if (post.body[i] === "#") {
            startIndices.push(i);
        }
        if (startIndices.length !== endIndices.length && post.body[i] == " ") {
            endIndices.push(i);
        }
    }

    for (let i = 0; i < startIndices.length; i++) {
      const word = post.body.substring(startIndices[i], endIndices[i]);
      const styledWord = word.style.color = "blue";

      post.body.replace(word, styledWord);
    }

    return post.body;
}

I attempted the code above but encountered an error.

TypeError: Cannot set properties of undefined (setting 'color')

Answer №1

It seems like you are attempting to apply a style to a string, which is not possible. Instead, consider wrapping the substrings in a span. Below is a more optimized function that achieves what you want to do.

function updateContent() {
  let content = article.content;
  let tags = content.match(/#[^\s]+/g); // extract all hashtags

  if (!tags) {
    // no keywords found, return original content
    return content;
  }

  // wrap each tag in a span with a specific class or style
  tags.forEach(tag => {
    content = content.replace(tag, `<span style="color: green">${tag}</span>`);
  });

  return content;
}

Answer №2

If you're attempting to modify styles for something that isn't an HTML element, you may encounter some challenges.

One workaround is to utilize regex to identify words starting with '#' and then substitute them with a span containing the word.

Afterwards, you can adjust the color of the span's content using CSS or JavaScript.

Here's a sample code snippet:

let postBody = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor lacinia urna eget gravida. Quisque magna nulla, fermentum fermentum od #keyword1 #keyword2 #keyword3 #keyword4 #keyword5'

const regex = /#[a-zA-Z0-9]+/g;
const color = "blue";

postBody = postBody.replace(regex, `<span style="color: ${color}">$&</span>`)

document.getElementById('postBody').innerHTML = postBody
<div id="postBody"></div>

Answer №3

post.body.substring() will give back a string. These strings are not considered as DOM elements and do not possess any DOM properties like style

To modify the color of specific substrings within your text, you must enclose them in an element tag like <span>. Then, you can apply a style or className to these span elements.

Answer №4

A great solution for your needs is this amazing library that perfectly aligns with your expectations. Not only does it match a regex pattern, but it also allows you to style the text exactly how you desire. With predefined patterns and the ability to customize your own, the possibilities are endless.

Imagine if your keywords were enclosed in square brackets or curly brackets, like so:

const sentence = "this is your sentence and here is [#keyword1] and [#keyword2];

Once you have installed the library by running either of these commands:

npm install react-substring-styler
or
yarn add react-substring-styler

You can easily format your text in the following way:

   <HighlightedText pattern={[{
      type: "squareBrackets",
      style: {
        color: "purple",
      }]}>{sentence}
   </HighlightedText>

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 process for verifying that a function has been invoked in a React error?

I encountered an issue while testing the axios.get function in react If you want to take a look at my code, feel free to visit this link https://codesandbox.io/s/oq7kwzrnj5 it("checking ajax call", () => { jest.mock('axios', () => { ...

"Exploring the relationship between Javascript objects and the '

function createNewRobot(robotIdentifier) { this.id = robotIdentifier; this.components = new Array(); this.gatherComponents = function() { $.getJSON('specific/url', function(data) { for(index in data.responses) { this.part ...

Issue with array push not working within nested Promise

I recently encountered an issue with my Express API route that retrieves an artist's details along with an array of releases for that artist. My current goal is to iterate over this array, extract each URL, and then make additional API calls to retri ...

Mobile devices are unable to properly implement the Jquery show/hide feature

Currently, I am working on a small Russian project and facing some challenges with the mobile version of my website: php8098.github.io/breakfast. The issue lies within the first slider where the play button should trigger a modal window to open. I urgentl ...

Vue.js v-cloak lifecycle method

Currently, I am working on a project where I have styled v-cloak with display: none, and it is decorating the body. As a result, everything remains hidden until the Vue instance is ready. I have created a component that inserts a chart (using highcharts). ...

What is the process of incorporating npm packages into a .NET Core project within Visual Studio 2019?

As I venture into the world of front end development using React in conjunction with .NET Core for backend, I find myself grappling with new tools and technologies. My task is to utilize Visual Studio 2019 for working with .NET Core, a development enviro ...

What are some strategies for ensuring the server stays running while executing npm run build?

I am currently managing a React app on a Digital Ocean "Droplet" and whenever I need to upload the latest version of the app from Github, I usually run npm run build (after using git pull). The issue arises when running npm run build as it overwrites the e ...

Having trouble displaying the Primevue dialog modal in Vue 3?

I am using [email protected] and [email protected] Main script import { createApp } from 'vue' import App from './App.vue' import router from './router' import PrimeVue from 'primevue/config'; import &apos ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...

Unable to trigger JavaScript function from ASP.NET MVC HTML view

I am encountering an issue with my ASP.NET MVC project where I am attempting to call a JavaScript function to record a user's selection from a listbox. Despite duplicating the JavaScript function in multiple places, it is still not being found. What c ...

"Exploring the world of Reactstrap: A

I am struggling to understand the documentation for Bootstrap and reactstrap as I have never used them before. For example, changing the Navbar color and background opacity has been a challenge because they require reserved keywords to be passed as props, ...

Angular2 (RC5) global variables across the application

I am seeking a solution to create a global variable that can be accessed across different Angular2 components and modules. I initially considered utilizing dependency injection in my `app.module` by setting a class with a property, but with the recent angu ...

Is it necessary to restart the IIS Site when altering the contents of index.html?

I am currently working on updating a website that runs on a Custom Designed CMS with files using the .asp extension. The site seems to be quite dated and is hosted on an IIS Server, which I do not have direct access to. The user has requested some changes ...

Develop a responsive design for a row of icons that automatically flows to a second line when the screen size is

Currently, I am utilizing Bootstrap 4 and attempting to design a row of 12 icons that are responsive. <div class="app-container"> <div class="row"> <div class="col-md-1"> <a class="" href="https://www.xxx.org.au"> < ...

Verifying that phone numbers and email addresses are accurate prior to submitting the form

As a PHP newcomer, I apologize if my question appears somewhat naive. Currently, I am working on a contact form that is functioning well, but I need to implement validation for two specific fields: the phone number and the email address. For the phone numb ...

Avoiding the collapse of the Bootstrap 4 navbar

Having trouble with the navbar collapsing on itself? The issue seems to occur around 1280px window size, but works fine when the window is wider or narrower. https://www.bootply.com/AcsaaqReAL .navbar-custom { background-color: #333333; border- ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...

Warning: Unidentified JavaScript alert(notification) encountered without declaring a

Imagine this scenario - when I type the following command: open google.com I need JavaScript to detect "open google.com" and prompt me with an alert. The challenge is figuring out how to generate an alert for just "google.com" without including "open". ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

PNPM does not automatically update to the latest minor or patch versions when using the caret (^) symbol during installation

When using PNPM, it appears to only install the version specified in package.json and does not automatically install the latest minor version available. For example, in my package.json file I have this dependency: "@tanstack/react-query": " ...