jQuery/Javascript 查找并替换所有实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9708653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:33:07  来源:igfitidea点击:

jQuery/Javascript find and replace all instances

javascriptjqueryreplace

提问by user1083320

Possible Duplicate:
Replace all instances of a pattern with regular expressions in Javascript / jQuery
How can I use jQuery to style /parts/ of all instances of a specific word?

可能的重复:
用 Javascript / jQuery 中的正则表达式替换模式的所有实例
如何使用 jQuery 为特定单词的所有实例设置样式/部分/?

Say I have the code:

说我有代码:

<div class="replace">
     <i>Blah</i>
     <u>Blah</u>
</div>

Now, I want to replace all the <within the div with something else.

现在,我想<用其他东西替换div 中的所有内容。

If I use $('#div').html().replace('<','somethingElse');it only replaces the first instance.

如果我使用$('#div').html().replace('<','somethingElse');它只替换第一个实例。

How can I replace all the instances?

如何替换所有实例?

Thanks

谢谢

回答by ShankarSangoli

Use regex

使用正则表达式

"anyString".replace(/</g,'somethingElse');

If you want to replace it inside the div then try this.

如果你想在 div 中替换它,那么试试这个。

$('#div').html($('#div').html().replace(/</g,'somethingElse'));