替换正文中的文字 [英] Replace words in the body text

查看:126
本文介绍了替换正文中的文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



像用hi替换hello一样,有一种方法可以替换位于HTML主体内的表元素中的普通文本? ?



请仅在没有 jQuery 的情况下使用 JavaScript

>解决方案

>在 innerHTML 上替换方法:

  document.body.innerHTML = document.body.innerHTML.replace('hello','hi'); 

请注意,这将替换 hello document.getElementById 或类似内容。



替换目标字符串的所有实例,使用一个简单的正则表达式和 g lobal标志:

  document .body.innerHTML = document.body.innerHTML.replace(/ hello / g,'hi'); 


Is there a way to replace the normal text within a table element that is placed within the body of the HTML?

Like replacing "hello" with "hi"?

Please only use JavaScript without jQuery.

解决方案

To replace a string in your HTML with another use the replace method on innerHTML:

document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');

Note that this will replace the first instance of hello throughout the body, including any instances in your HTML code (e.g. class names etc..), so use with caution - for better results, try restricting the scope of your replacement by targeting your code using document.getElementById or similar.

To replace all instances of the target string, use a simple regular expression with the global flag:

document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');

这篇关于替换正文中的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆