javascript实现repalceAll

a = "testtesttest http://baidu.comhttp://baidu.com,test"
rgx=/(<a.)?((((http|ftp|https)://)|(www.))+[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#][w-@?^=%&/~+#])?)('?>?.*</a>)?([/]|[W])/gi;

a.replace(rgx, "~hh~")

想要的效果是是"testtesttest ~hh~,~hh~,test"
实际上只替换掉了第一个,如何实现全部替换呢?

阅读 3.3k
3 个回答

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);
}

};


// eg:
var a = "aaabbbbaaabbcccbdddd";
// 把所有的"a"替换为"v"
a = a.replaceAll("a","v");

'哈哈哈-sss-fdf-蛤蛤蛤'.replace(/-/g,"")

String.prototype.replaceAll = function(s1, s2){
    return this.replace(new RegExp(s1, 'gm'),s2);
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题