jQuery if div contains this text, replace that part of the text
Asked Answered
L

5

92

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

The structure looks like this:

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

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

Lambda answered 4/7, 2012 at 7:43 Comment(1)
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.Midwinter
G
163

You can use the 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"); 
});​​​​​

Here's a working example.

Gyrostatic answered 4/7, 2012 at 7:45 Comment(4)
You can use regex /iwantreplacethis/g for all ocurencesRori
Thank you so much for this :) one simple question: why doesn't this work without the returnSprage
@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.Gyrostatic
This solve a complex issue for me, thank youBreadthways
D
13

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.
</div>

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.

Drews answered 4/7, 2012 at 7:46 Comment(0)
T
10

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

jQuery(function($){

    // 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");  

    });
});

Here is full example: https://blog.hfarazm.com/remove-unwrapped-text-jquery/

Tireless answered 17/4, 2018 at 16:28 Comment(0)
P
8
var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));
Pessimism answered 4/7, 2012 at 7:45 Comment(0)
Z
4

You can use the contains 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"));

​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Zaratite answered 4/7, 2012 at 7:47 Comment(1)
this will replace more than one word if my string contains more than one target words, what will be then?Spectacle

© 2022 - 2024 — McMap. All rights reserved.