0

I'm using replace in javascript thats good but when add link url replace I do not want to change the link can do it?

var someString = "The stack overflow good site http://stackoverflow.com ";
var replaced = somestring.replace(/the/g, "ing").replace(/s/g, "j");

Is it possible to change that without changing the link?

  • `somestring` is undefined, you meant `someString`, camelCased. And yeah regex can do that you could adapt this regex which only exclude a specific domain http://stackoverflow.com/questions/15663104/url-regex-excluding-a-specific-domain-not-matching-correctly – GillesC Jul 22 '14 at 18:22

1 Answers1

0

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"
Khalid
  • 4,730
  • 5
  • 27
  • 50