jQuery si div contiene este texto, reemplace esa parte del texto

Like the title says, I want to replace a specific part of the text in a div.

La estructura se ve así:

<div class="text_div">
    This div contains some text.

And I want to replace only "contains" with "hello everyone", for example. I can't find a solution for this.

preguntado el 04 de julio de 12 a las 08:07

What about if the text was 'This div contains some text which contains some letters' and I wish to change the 1st contains, not the 2nd one. Or just select any word and it will be changed by predefined one. -

5 Respuestas

Puede utilizar el text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

​$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 

Aquí hay una ejemplo de trabajo.

Respondido 04 Jul 12, 08:07

You can use regex /iwantreplacethis/g for all ocurences - Aiphee

Thank you so much for this :) one simple question: why doesn't this work without the return - aaron matthews

@AaronMatthews This answer was a very long time ago but I believe it would be because the jQuery text method, when passed a function, sets the text of the selection to the return value of that function. Without the return the text would be replaced with nothing. - James Allardice

If it's possible, you could wrap the word(s) you want to replace in a span tag, like so:

<div class="text_div">
    This div <span>contains</span> some text.

You can then easily change its contents with jQuery:

$('.text_div > span').text('hello everyone');

If you can't wrap it in a span tag, you could use regular expressions.

Respondido 04 Jul 12, 08:07

Very simple just use this code, it will preserve the HTML, while removing unwrapped text only:


    // Replace 'td' with your html tag
    $("td").html(function() { 

    // Replace 'ok' with string you want to change, you can delete 'hello everyone' to remove the text
          return $(this).html().replace("ok", "hello everyone");  


Aquí hay un ejemplo completo: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

Respondido 17 Abr '18, 17:04

var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));

Respondido 04 Jul 12, 08:07

Puede utilizar el contiene selector to search for elements containing a specific text

var elem = $('div.text_div:contains("This div contains some text")')​;
elem.text(elem.text().replace("contains", "Hello everyone"));


Respondido 04 Jul 12, 08:07

this will replace more than one word if my string contains more than one target words, what will be then? - Tamaghna Banerjee

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.