1

I'm trying to create an autolink feature in javascript that automatically turns urls into links while the user types (ContentEditable div).

I use this regex:

var text = 'Some text containing URLs';
var exp = /(\b(http):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
var newtext = text.replace(exp,"<a href='$1'>$1</a>");

The code above works fine, but because the code gets called each time a user types, recursion occurs:

<a href='<a href='<a href=' etc.

How can I avoid this from happening while still having the script update the text as a user types?

So the question is (thanks @putvande): how do I check if a URL doesn't already contain:

<a href='... 

(I'm not really handy with regex)

Portable Page
  • 239
  • 3
  • 7
  • You need to check with your Regex if there are already `` tags in your code. – putvande Jul 27 '13 at 13:18
  • 1
    I found a non-regex solution to my problem, before the regex function I strip all tags. See my fiddle jsfiddle.net/gerbenzomp/UJMeR/3 Might not be the most elegant solution, so I'm still very interested in a regex-only solution. – Portable Page Jul 27 '13 at 15:01
  • Hay @Gerben did you fix this ? i need a solution im working on this – dhee Jun 18 '14 at 10:21

1 Answers1

0

You can match only those URL patterns that aren't prefixed with a > or a '. While this may not be 100% foolproof, it should be good enough to get you started.

function urlify(text) {
    var exp = /^\>(\b(http):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>");
}

On calling it:

urlify('Some text http://example.com containing URLs');

returns "Some text <a href='http://example.com'>http://example.com</a> containing URLs"

urlify("Some text <a href='http://example.com'>http://example.com</a> containing URLs");

returns "Some text <a href='http://example.com'>http://example.com</a> containing URLs"

S.Walker
  • 166
  • 1
  • 8
techfoobar
  • 65,616
  • 14
  • 114
  • 135