skip to Main Content

I want to change color of a particular substring from a post.
eg:-

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 above example is the post then i want to change the style of the keywords. I am using Next.js.

function handleBody(){
    var arr1=[],arr2=[];
    for(let i=0;i<post.body.length;i++){
        if(post.body[i]==="#"){
          arr1.push(i);
        }
        if(arr1.length!==arr2.length && post.body[i]==" " ){
            arr2.push(i);
        }
    }
    for(let i=0;i<post.body.length;i++){
      const trial2 =  post.body.substring(arr1[i], arr2[i])
      const trial =  post.body.substring(arr1[i], arr2[i]).style.color ="blue";

      post.body.replace(trial2, trial)
    }
    return post.body
  }

I have tried as above but its giving an error

TypeError: Cannot set properties of undefined (setting ‘color’)

3

Answers


  1. You are trying to set style of a string type… which isn’t possible, instead you can wrap the substrings in a span, here is a more optimized function for what you want to do.

    function handleBody() {
      let body = post.body;
      let keywords = body.match(/#[^s]+/g); // extract all hashtags
    
      if (!keywords) {
        // no keywords found, return original body
        return body;
      }
    
      // wrap each keyword in a span with a class or style
      keywords.forEach(keyword => {
        body = body.replace(keyword, `<span style="color: blue">${keyword}</span>`);
      });
    
      return body;
    }
    
    Login or Signup to reply.
  2. post.body.substring() will return a string. Strings are not DOM elements, and does not have DOM properties like style

    In order to change the color of any substrings in your text, you would need to wrap them in an element tag, such as <span>. You could then add a style or className to these span elements.

    Login or Signup to reply.
  3. You are trying to change styles for something that is not an HTML element.

    You can use regex to select the words that begin with ‘#’ and then replace them with a span containing the word.

    Then you can change the color of the content of the span with CSS or with JS.

    Here is an example:

    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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search