如何在HTML中替换所有的单词为另一个单词
JavaScript的 replace()方法 用于替换字符串中字符或整个字符串的所有出现。它会搜索与特定值或正则表达式相对应的字符串,并返回一个具有修改后值的新字符串。
可以使用 正则表达式 代替字符串来定义要替换的字符或字符串。正则表达式是一个包含特殊符号和字符的字符串,用于从给定数据中查找和提取所需信息。正则表达式基本上是包含字符和特殊符号的字符串,可以帮助选择所需的值。
需要注意的是 replace() 函数只会替换指定值的第一个出现。为了替换所有出现,需要使用 全局修饰符 。
语法:
string.replace(valueToBeReplaced, newValue)
其中’valueToBeReplaced’可以是字符串值或正则表达式。
示例1: 使用replace()函数将字符串’Hello’替换为’Hi’
<h1>Hello welcome to our blog!</h1>
<p>
Hello today we shall learn about
replace() function in JavaScript
Click on the button below to replace
hello with hi.
</p>
<button onclick="rep()">Replace</button>
<script>
// Replace the first "Hello"
// in the page with "Hi"
function rep() {
document.body.innerHTML
= document.body.innerHTML
.replace("Hello", "Hi");
}
</script>
输出:
如上所示的输出中,只有第一个出现的“Hello”被替换为“Hi”。要替换所有出现,必须使用全局修饰符。
示例2: 使用replace()函数将字符串“Hello”的所有出现都替换为“Hi”。
<h1>Hello welcome to our blog!</h1>
<p>Hello today we shall learn about
replace() function in JavaScript
Click on the button below to
replace hello with hi.
</p>
<button onclick="rep()">Replace</button>
<script>
// Replace all the "Hello"
// in the page with "Hi"
function rep() {
document.body.innerHTML =
document.body.innerHTML
.replace(/Hello/g, "Hi");
}
</script>
输出:
下一个示例中,全局修改器和“i”修改器同时使用,以确保无论大小写如何,都替换掉给定单词的所有出现。
示例3: 使用replace()函数,无论大小写如何,都将字符串‘Hello’的所有出现替换为‘Hi’。
<h1>Hello welcome to our blog!</h1>
<p>
Hello today we shall learn about
replace() function in JavaScript
Click on the button below to
replace hello with hi.
</p>
<button onclick="rep()">
Replace
</button>
<script>
// Replace all the "Hello" in the
// page with "Hi" irrespective of
// the case
function rep() {
document.body.innerHTML =
document.body.innerHTML
.replace(/Hello/gi, "Hi");
}
</script>
输出:
示例4: 使用replace()函数将特定标签上所有出现的字符串’Hello’替换为’Hi’。
<h1 id="h1">Hello welcome to our blog!</h1>
<p>Hello today we shall learn about
replace() function in JavaScript
Click on the button below to replace
hello with hi.
</p>
<button onclick="rep()">Replace</button>
<script>
// Replace all the "Hello" in the
// page with "Hi" irrespective of the case
// with the h1 tag
function rep() {
document.getElementById('h1')
.innerHTML = document.getElementById('h1')
.innerHTML
.replace(/Hello/g, "Hi");
}
</script>
输出:
如输出所示,代码中 h1 标签部分中的“Hello”出现次数被替换为“Hi”。