Posted in JavaScript

[Javascript] Regular Express for URL and Email detection in a sentence.

javascript

There are many ways to detect URL(s) in a sentence:

  • Use validUrl lib: Refer detail at here

This lib has a disadvantage that is it can analyze a URL is valid or not. It means if you put that URL in a sentence such as “Hello http://www.saothienhat.wordpress.com site !”, it cannot detect the URL

  • Use below Regular Express:
function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;
}

Using above Regular Express, you can detect URL(s) as well as Email(s) in a sentence. You can modify this Regular Express for your jobs :).

You can refer detail of Regular Express guide at here

Like and Share if it is helpful 🙂

Leave a comment