JS替换字符串中所有指定的字符(串)

JavaScript中replace() 方法如果直接用str.replace(“-“,”!”) 只会替换第一个匹配的字符.
而str.replace(/-/g,”!”)则可以全部替换掉匹配的字符(g为全局标志)。

String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) {
    if(!RegExp.prototype.isPrototypeOf(reallyDo)) {
        return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi" : "g")), replaceWith);
    } else {
        return this.replace(reallyDo, replaceWith);
    }
}
  • string:字符串表达式包含要替代的子字符串。
  • reallyDo:被搜索的子字符串。
  • replaceWith:用于替换的子字符串。

用法

var string = 'abcdefabcdefabcdef';
console.log(string.replaceAll('b',"0",false));//结果:a0cdefa0cdefa0cdef

参考

http://fuleonardo.iteye.com/blog/339749

猜你喜欢

转载自blog.csdn.net/demonliuhui/article/details/79495474