how can I compare text and paragraphs and javascript

1

I need to compare a word that is inside a variable, with the content of a paragraph, to be able to change the color .. I do not have even the palest idea of how it is done ... an example would be

var elemento = $('h1.ht-main-title').find('span');
var texto = $(elemento).text();

to get the word to compare within a div .. for example

<div>un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas "Letraset", las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum</div>

in this case for example if the word that is in the variable is Lorem, I need to paint it in red .. Any idea how to start?

    
asked by Hernan Chaparro 15.11.2018 в 01:24
source

1 answer

0

Use String.replace() and a regular expression. For example:

var elemento = $('h1.ht-main-title').find('span');
var contento = $(elemento).html();
var regex = /Lorem/gi;
contento = contento.replace(regex, "<span style='color:red'>Lorem</span>")
elemento.html(contento);

But there is a problem with capital letters. If you want to maintain the integrity of the word, you need to use $ 1:

contento = contento.replace(regex, "<span style='color:red'>$1</span>")

Reference: link

    
answered by 15.11.2018 / 04:37
source