问题描述
像用hi替换hello一样,有一种方法可以替换位于HTML主体内的表元素中的普通文本? ?
请仅在没有 jQuery 的情况下使用 JavaScript 。
>在上替换方法:
document.body.innerHTML = document.body.innerHTML.replace('hello','hi');
请注意,这将替换 hello
替换目标字符串的所有实例,使用一个简单的正则表达式和
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
g
lobal flag:
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');
这篇关于替换正文中的文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!