当前位置:编程学习 > JS >>

javascript字符替换(支持中文汉字替换)

要在js中进行字符或字符串替换我们可以用到replace()方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

stringObject.replace(regexp/substr,replacement)

利用replace正则表达式替换

<html>
    <script language="JavaScript1.2">
    <!--
    var myString = new String("This is a test");

    var myRegExp = /is/g;

    var newString = myString.replace(myRegExp, "test www.zhutiai.com ");

    document.write('Notice the last name in the original string, ' + myString);

    document.write(', was replaced and is now '+ newString);

    document.close();

    -->

    </script>
</html>

也可以直接用replace进行替换

<html>
<head>
<title>Using the replace() method of the String object</title>
<script type="text/网页特效" language="javascript">
<!-- //
var originalString = "A ab abc abcd";
var replacedString = "a";
var replacementString = "z";

var newString = originalString.replace(replacedString, replacementString);

document.write("<h3>" + newString + "</h3");
// -->
</script>
</head>
<body>

</body>
</html>

对于中文我们最好用正则哦。

补充:网页制作,js教程
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,