Javascript 如何使用 jQuery 查找和替换文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4455606/
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-08-23 12:28:18  来源:igfitidea点击:

How to Find text and replace using jQuery

javascriptjqueryreplace

提问by jrutter

Im trying to find a solution to search for a text string "Tony" contained in the DOM and replace it with a text String "Tiger".

我试图找到一种解决方案来搜索包含在 DOM 中的文本字符串“Tony”并将其替换为文本字符串“Tiger”。

Anyone have any insight or ideas of how to do so? Im guessing it will take an each statement coupled with a replace function and possibly contains?

任何人都对如何做到这一点有任何见解或想法?我猜它需要一个 each 语句加上一个替换函数并且可能包含?

Thanks Jake

谢谢Hyman

回答by exoboy

You can use this to search all children of the body element and replace the text...

您可以使用它来搜索 body 元素的所有子元素并替换文本...

$('body').children().each(function(){$(this).text( $(this).text().replace('Tony','Tiger') )});

It uses jQuery. It also should only alter the textual content of elements and none of the HTML formatting...

它使用jQuery。它也应该只改变元素的文本内容而不是 HTML 格式......

You can also use this method which uses a RegExp and will get all nested elements:

您还可以使用此方法,该方法使用 RegExp 并获取所有嵌套元素:

 $('body').html( $('body').html().replace(/Tony/gi,'tiger') );

回答by slolife

Page wide, you can use something like this:

页面范围内,您可以使用以下内容:

var $body = $('body');
var html = $body.html();
var newHtml = html.replace('Tony', 'Tiger');
$body.html(newHtml);

Or, if you have a more specific container, use jQuery to select that child container and do the same thing.

或者,如果您有一个更具体的容器,请使用 jQuery 选择该子容器并执行相同的操作。

Either way, it is sort of a shotgun approach. It will change the string in both visible text and html element attributes. A more detailed approach might be needed if the string needed to be ignored in certain locations.

无论哪种方式,它都是一种霰弹枪方法。它将更改可见文本和 html 元素属性中的字符串。如果需要在某些位置忽略字符串,则可能需要更详细的方法。

回答by Simon

Is it possible to couple this with a server-side solution? You could wrap every occurence of the word server side with a special class, like <span class="replaceme">texttoreplace</span>.

是否可以将其与服务器端解决方案结合使用?你可以用一个特殊的类来包装单词服务器端的每一次出现,比如<span class="replaceme">texttoreplace</span>.

Running a javascript replace on the resulting classes only should speed things up.

在生成的类上运行 javascript 替换只会加快速度。