Beach Code Beach Code - 2 months ago 6
Javascript Question

How to parse a given string by replaces URL's with links, emails with mail-to links and hash tags with empty links in Javascript

How to write a function which parses a given string by removing HTML tags inside it and freshly replacing URL's with links, emails with mail-to links and hash tags with empty links in JavaScript.

Answer
function parseString (text) {

   var urls  = /(\b(((https?|ftp):\/\/)|www.)[A-Z0-9+&@#\/%?=~_|!:,.;-]*[-A-Z0-9+&@#\/%=~_|])/gim;
   var emails = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
   var hashTags = /((^|[ ])#[a-zA-Z0-9\d-]{1,500})/gim;; 


    text = text ? String(text).replace(/<[^>]+>/gm, '') : ''; // Remove all the html tags

    if (text.match(urls)) {
       text = text.replace(urls, "<a href=\"$1\" target=\"_blank\">$1</a>");
    }

    if (text.match(emails)) {
      text = text.replace(emails, "<a href=\"mailto:$1\">$1</a>");
    }

    if (text.match(hashTags)) {
      text = text.replace(hashTags, "<a href=\"javascript:;\" target=\"_blank\">$1</a>");
    }

    return text.replace(/\n\r?/g, '<br />');

  }

This will parses everything and returns you a proper parsed string.

var string = "hello this is website http://one.com and iamemail@gmail.com and #niceone";
console.log(parseString(string)); 

Working Demo : https://jsbin.com/buhenob/1/edit?html,js,console,output

Comments