Search code examples
javascripturlhyperlinkhref

How to get the url string from a text javascript


How can I get the url string from a generated text. For example I have generated a text

text =  "This is my sample text try http:\/\/sample.com\/23411";

convertedString = "This is my sample text try http://sample.com/23411";

I want to do this

var disp = "";

disp += "This is my sample text try";
disp += "<a href = 'http://sample.com/23411'>http://sample.com/23411</a>";

result

This is my sample text try http://sample.com/23411


Solution

  • Easiest way would be to use a regex:

    disp = text.replace(/(http:\/\/[^ ]+)/, "<a href='$1'>$1</a>");
    

    See it here in action: http://jsfiddle.net/49YFF/