add exception in javascript

145 views Asked by At

I have the following code:

function replaceURLWithHTMLLinks(text) {
var re = /(\(.*?)?\b((?:https?|ftp|file):\/\/[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/ig;
return text.replace(re, function(match, lParens, url) {
    var rParens = '';
    lParens = lParens || '';

    // Try to strip the same number of right parens from url
    // as there are left parens.  Here, lParenCounter must be
    // a RegExp object.  You cannot use a literal
    //     while (/\(/g.exec(lParens)) { ... }
    // because an object is needed to store the lastIndex state.
    var lParenCounter = /\(/g;
    while (lParenCounter.exec(lParens)) {
        var m;
        // We want m[1] to be greedy, unless a period precedes the
        // right parenthesis.  These tests cannot be simplified as
        //     /(.*)(\.?\).*)/.exec(url)
        // because if (.*) is greedy then \.? never gets a chance.
        if (m = /(.*)(\.\).*)/.exec(url) ||
                /(.*)(\).*)/.exec(url)) {
            url = m[1];
            rParens = m[2] + rParens;
        }
    }
    return lParens + "<a href='" + url + "'>" + url + "</a>" + rParens;
});
}
var elm = document.getElementById('pls');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);

this script managed to change the url text into a hyperlink, but the script is problematic in displaying images, this is the result:

before I place the javascript code:

   <img class="b_img" src="http://www.example.com/images.jpg" alt="images">

after I place the javascript code:

    <img class="b_img" src="src="<a href='http://www.example.com/images.jpg>http://www.example.com/images.jpg</a>"" alt="images">

I don't know how to fix it, thank's in advance

0

There are 0 answers