1

I am using regex to replace all url in string to <a href="url">url</a>.

For that I am using

if(!String.linkify) {
    String.prototype.linkify = function() {

        // http://, https://, ftp://
        var urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;

        // www. sans http:// or https://
        var pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;

        // Email addresses
        var emailAddressPattern = /[\w.]+@[a-zA-Z_-]+?(?:\.[a-zA-Z]{2,6})+/gim;

        return this
            .replace(urlPattern, '<a href="$&">$&</a>')
            .replace(pseudoUrlPattern, '$1<a href="http://$2">$2</a>')
            .replace(emailAddressPattern, '<a href="mailto:$&">$&</a>');
    };
}

and

mystr.linkify();

it's from here , https://stackoverflow.com/a/7123542/1602333

it works good unless I have img tag in my string , it replaces

<img src="imgurl"/> to <img src="<a href="imgurl">imgurl</a>"

Which change should I do to my regex to not replace urls which are part of some tag attribute ?

Any help would be great.

Community
  • 1
  • 1
MohK
  • 1,873
  • 1
  • 18
  • 29

1 Answers1

1

Use Autolinker.js, it is known to be reliable with linkifying.

See the description part about links inside other tags/attributes:

Will properly handle HTML input. The utility will not change the href attribute inside anchor (<a>) tags (or any other tag/attribute for that matter), and will not accidentally wrap the inner text of an anchor tag with a new one (which would cause doubly-nested anchor tags).

Here is an example of using it:

var linkedText = Autolinker.link(input_html, { className: "myLink" } );
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563