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
You are trying to set style of a
string
type… which isn’t possible, instead you can wrap the substrings in aspan
, here is a more optimized function for what you want to do.post.body.substring()
will return astring
. Strings are not DOM elements, and does not have DOM properties likestyle
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.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: