Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple javascript find and replace

is there a straightforward method for searching within a div for a specific string and replacing it with another? I cannot use .replaceWith alone because there are other elements within the div I need to preserve. I've tried various javascript methods found here to no avail.

So something like:

$('#foo').find('this string').replaceWith('this other string');

for:

<div id="foo"><div id="child">Other Element</div>this string</div>

Thanks.

like image 508
pac Avatar asked May 12 '11 19:05

pac


2 Answers

Try this:

var foo = $('#foo').html();

foo = foo.replace('this string', 'this other string');

$('#foo').html(foo);

Fiddle: http://jsfiddle.net/maniator/w9GzF/

like image 185
Naftali Avatar answered Oct 10 '22 06:10

Naftali


This replaces all occurrences:

var $foo = $('#foo'),
    fooHtml = $foo.html();

$foo.html(fooHtml.replace(/this string/g, 'this other string'));
like image 34
Code Maverick Avatar answered Oct 10 '22 07:10

Code Maverick