本文介绍JavaScript中replace函数的用法,通过示例演示如何将字符串中的指定子串替换为新的内容。
JavaScript使用replace替换字符串
本文介绍JavaScript中replace函数的用法,通过示例演示如何将字符串中的指定子串替换为新的内容。
示例代码将文本“Visit Microsoft”中的“Microsoft”替换为“jb51.net”。
<!DOCTYPE html>
<html>
<body>
<p>
Click the button to replace "Microsoft"
with "jb51.net" in the paragraph below:
</p>
<p id="demo">Visit Microsoft!</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML;
var n=str.replace("Microsoft","jb51.net");
document.getElementById("demo").innerHTML=n;
}
</script>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。