How to change color of inner text of HTML var var using JavaScript?

I want to color all the words that I select in my input from the rows of the table. The line table contains a line of paragraphs.

The problem with this code, it just colors 1 word not all words for paragraphs, and it adds the word I want to color in before the paragraph for exp, if I have two paragraphs, it will color one word from each paragraph, and it will concatenate the word I chose to color it at the beginning of the second paragraph.

my javascript code is:

var word ='pregnant'; 
var a = row["Abstract"].substring(0, row["Abstract"].indexOf(word));
var b = row["Abstract"].substring(row["Abstract"].indexOf(word) + word.length);

HTML:

'<span style="color: black;">'+ a +'</span>' + '<span style="color: red;">'+ word +'</span>' + b
+4
source share
1 answer

, , , 2. a , b .

, .

regex, , :

var org = "Lorem replace ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore replace et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi replace ut aliquip ex ea replace commodo consequat";
var word = "replace";

var result = org.replace(new RegExp(word, "g"), `<span style="color: red;">${word}</span>`);
console.log(result);
Hide result
0

Source: https://habr.com/ru/post/1693522/


All Articles