jQuery替换html页面中出现的所有字符串

Cal*_*mer 21 html javascript jquery replace

我正在开发一个项目,我需要用另一个字符串替换所有出现的字符串.但是,我只想替换字符串,如果它是文本.例如,我想转此......

<div id="container">
  <h1>Hi</h1>
  <h2 class="Hi">Test</h2>
  Hi
</div>
Run Code Online (Sandbox Code Playgroud)

成...

<div id="container">
  <h1>Hello</h1>
  <h2 class="Hi">Test</h2>
  Hello
</div>
Run Code Online (Sandbox Code Playgroud)

在该示例中,除了作为h2类的"Hi"之外,所有"Hi"被转换为"Hello".我试过了...

$("#container").html( $("#container").html().replace( /Hi/g, "Hello" ) )
Run Code Online (Sandbox Code Playgroud)

...但是它也取代了html中出现的所有"Hi"

j08*_*691 17

这个:

$("#container").contents().each(function () {
    if (this.nodeType === 3) this.nodeValue = $.trim($(this).text()).replace(/Hi/g, "Hello")
    if (this.nodeType === 1) $(this).html( $(this).html().replace(/Hi/g, "Hello") )
})
Run Code Online (Sandbox Code Playgroud)

产生这个:

<div id="container">
    <h1>Hello</h1>
    <h2 class="Hi">Test</h2>
    Hello
</div>
Run Code Online (Sandbox Code Playgroud)

jsFiddle例子

  • 如果有嵌套的 HTML 标签,这将不起作用,例如 `&lt;h2 class="Hi"&gt;Test &lt;span class="Hi"&gt;&lt;/span&gt;&lt;/h2&gt;` (4认同)

Cyr*_*art 9

结果很好:

function str_replace_all(string, str_find, str_replace){
try{
    return string.replace( new RegExp(str_find, "gi"), str_replace ) ;      
} catch(ex){return string;}}
Run Code Online (Sandbox Code Playgroud)

而且更容易记住......


Sau*_*tel 7

 replacedstr = str.replace(/needtoreplace/gi, 'replacewith');
Run Code Online (Sandbox Code Playgroud)

needtoreplace不应该舍入 '