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

Incorporating a JavaScript file into Angular

I'm looking to incorporate a new feature from this library on GitHub into my Angular project, which will enhance my ChartJS graph. @ViewChild('myChart') myChart: ElementRef; myChartBis: Chart; .... .... const ctx = this.myChart.nativeEleme ...

When trying to set up Plaiceholder in a Next.js/Webpack 5 environment, you may encounter the following issue: "Error: Module not found - Can't resolve 'child_process

While working on my Next.js application, I encountered an issue after installing/importing Plaiceholder for generating placeholder images. The error message I received is: Module not found: Can't resolve 'child_process' Node version: 14.18. ...

To ensure each row in the data grid component is distinct, it is necessary for them to possess a unique identifier property. Another option is to utilize the getRowId

I'm just starting out with React. I keep encountering an Error Mui: The data grid component is asking for a unique ID property for all rows. You can also use the getRowId prop to define a custom id for each row. I've tried a few things but not ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

How can I target all ul elements except those contained within a div with a specific class using CSS?

In my global.scss file, I have defined global styles for ul elements as shown below: ul { list-style: none; margin: 0; padding: 0; } However, I am trying to find a way to style all ul elements except those within a specific jodit-wrapper class ...

(node:2824) UnhandledPromiseRejectionWarning: ReferenceError: The variable "role" has not been declared

I am currently in the process of getting my discord bot up and running again. The issue is that he is old, and in the previous version, this functionality worked. However, after reading other posts, I discovered that in order to make it work, I need to u ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

What could be causing the issue of loading text not appearing in Vue.js?

I have the following code snippet in my application: <div id="app"> <button v-if="!isPrepared && !isLoading" @click="startLoading()">Start Loading</button> <div v-if="isLoading">Lo ...

The React Native Android app encountered an error loading the JS bundle: updates made to index.android.js are not reflecting in the generated APK file

Setting up a react-native android project on my Windows machine has been successful so far. To run the project, I use the command react-native run-android and then the installed apk is generated on my phone. After making some changes in the index.android. ...

Having trouble retrieving data from redux toolkit using typescript

I've been diving into the world of Typescript by building a simple todo app using React, Redux-toolkit, and Typescript. One issue I encountered is when trying to access data from the store with useSelector. The retrieved object contains the desired va ...

How to add a design to an image using a fabric pattern on a shirt

https://i.stack.imgur.com/ocWBp.png If I have an image and want to fill it with fabric below. And the final image will look like this: https://i.stack.imgur.com/vVv0I.png I just want to fill a pattern in a shirt like shown in this demo. Is there ...

Show a single item from the database sequentially and cycle through the rest in a timed loop

I am working on a project that requires displaying specific details on the main screen of my office. The challenge I'm facing is that I need to show only one item at a time and then cycle through each item within a specified time period. Below are th ...

Achieve a perfectly centered and responsive image placement on a webpage accompanied by a countdown timer

I've been trying to design an HTML page with a countdown feature, and I want to place an image above it that is centered and responsive. Despite my efforts, I haven't been able to achieve the desired responsiveness. I envision it looking like thi ...

Giant Slide - navigate directly to a particular slide using a link

Hey there, I am currently working on incorporating the Superslide slider for fullscreen images in my website. My goal is to have a mostly text-free site where users can navigate through the images using the main menu or jump to a specific image within the ...

Display an iframe using React in multiple areas across the app with the same state

Within my React scenario, we display a BI dashboard using an iframe on the page, allowing users to interact with the frame and potentially filter the BI data. I've developed a feature that enables this iframe to expand into a full-screen dialog for en ...

jquery animation does not reset after event occurs

My script is functioning well to animate my elements, but I am facing an issue where when the function is called again after a timer, the elements move to their correct positions but do not initiate a new animation. The goal of the function updateFlights( ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

Every time Fetch() is called in Node.js, a fresh Express session is established

Here is a snippet of code from a webshop server that includes two APIs: ./login for logging in and ./products to display products. The products will only be displayed after a successful login. The server uses TypeScript with Node.js and Express, along wit ...

Techniques for parsing a String in Objective-C

I am looking to parse a string to replace certain elements within it. If the string contains an <ol> tag, I want to specifically focus on replacing the <li> elements with numbers. I understand that I can utilize the rangeOfString method to c ...

What is the best location to initialize a fresh instance of the Firebase database?

Is the placement of const db = firebase.database() crucial in a cloud function script? For instance, in a file like index.ts where all my cloud functions are located, should I declare it at the top or within each individual function? const db = firebase. ...