简单的javascript查找和替换

pac*_*pac 6 javascript jquery replace

是否有一种直接的方法在div中搜索特定字符串并将其替换为另一个字符串?我不能单独使用.replaceWith,因为我需要保留div中的其他元素.我试过这里找到的各种javascript方法无济于事.

所以类似于:

$('#foo').find('this string').replaceWith('this other string');
Run Code Online (Sandbox Code Playgroud)

对于:

<div id="foo"><div id="child">Other Element</div>this string</div>
Run Code Online (Sandbox Code Playgroud)

谢谢.

Cod*_*ick 9

这取代了所有出现的事件:

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

$foo.html(fooHtml.replace(/this string/g, 'this other string'));
Run Code Online (Sandbox Code Playgroud)

  • +1替换所有不仅仅是第一次出现 (2认同)

Nea*_*eal 7

试试这个:

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

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

$('#foo').html(foo);
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/maniator/w9GzF/

  • 像这样设置`html(..)`会重新创建DOM元素,这意味着你会丢失以前附加的数据或这些元素上的事件. (2认同)