js replaceAll

JS中有时会需要使用replace将字符串中的某些字符进行替换,replace一次只能替换一个,因此想到使用replaceAll一次性替换所有的。

但是JS中没有定义replaceAll方法,因此需要自己进行定义。

代码如下:

<html>
    <body>
        <input type="button" value="测试" onclick="test()">
        
        <script type="text/javascript">

            String.prototype.replaceAll  = function(s1,s2){     
                return this.replace(new RegExp(s1,"gm"),s2);     
            }   

            function test(){
                var val = "187,0973,2211";
                alert(val.replaceAll(",", ""));
            }

        </script>
    </body>
</html>

 

posted on 2016-07-26 18:07  禁忌夜色  阅读(10188)  评论(1编辑  收藏  举报

导航