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

JqueryTextReplaceContains

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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.

Solution 3 - Jquery

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/

Solution 4 - Jquery

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

Solution 5 - Jquery

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanielView Question on Stackoverflow
Solution 1 - JqueryJames AllardiceView Answer on Stackoverflow
Solution 2 - JquerygrcView Answer on Stackoverflow
Solution 3 - JqueryhfarazmView Answer on Stackoverflow
Solution 4 - JqueryFabrizio CalderanView Answer on Stackoverflow
Solution 5 - Jqueryz33mView Answer on Stackoverflow