You can define a method that changes the url to something, and then replace your string and finally put the urls where they were before
String.prototype.replaceStr = function (reg, strOrCallBack) {
var str = this;
var links = [];
var found = true;
while(found) {
found = false;
str = str.replace(/(https?:\/\/[^\s]+)/g, function(url) {
links.push(url);
found = true;
return "(--" + (links.length-1) + "--)";
});
}
str = str.replace(reg, strOrCallBack);
return links.reduce(function (result, item, index) {
return result.replace("(--" + index + "--)", item);
}, str);
}
You can have on your string as many urls as you want and all the urls will stay the same after calling the method replaceStr
var somestr = "Welcome to stack overflow --> http://stackoverflow.com";
var replaced = somestr.replaceStr(/too/g, "at").replaceStr(/o/g, "0");
// "Welc0me t0 stack 0verfl0w --> http://stackoverflow.com"