Issue
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')
Solution
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;
}
Answered By - SamHoque
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.