我在javascript中使用replace那个好但是当添加链接url替换我不想改变链接可以做到吗?
var someString = "The stack overflow good site http://stackoverflow.com ";
var replaced = somestring.replace(/the/g, "ing").replace(/s/g, "j");
是否可以在不更改链接的情况下进行更改?
答案 0 :(得分:0)
您可以定义一个方法,将网址更改为某个内容,然后替换您的字符串,最后将网址放在原来的位置
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);
}
您可以在字符串上添加任意数量的网址,并且在调用方法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"