-3

I'm looking at a 'to do' list application that uses JavaScript. One of the functions converts text in to a hyperlink when https, https or ftp is present.

I'd like to expand this so if my text contains # followed by any 5 digit number, that becomes a link as well. The URL should be http://192.168.0.1/localsite/testschool/search.php?id=ID

where ID is the # and 5 digit number.

This is the current Javascript:

function prepareHtml(s)
{
    // make URLs clickable
    s = s.replace(/(^|\s|>)(www\.([\w\#$%&~\/.\-\+;:=,\?\[\]@]+?))(,|\.|:|)?(?=\s|&quot;|&lt;|&gt;|\"|<|>|$)/gi, '$1<a href="http://$2" target="_blank">$2</a>$4');
    return s.replace(/(^|\s|>)((?:http|https|ftp):\/\/([\w\#$%&~\/.\-\+;:=,\?\[\]@]+?))(,|\.|:|)?(?=\s|&quot;|&lt;|&gt;|\"|<|>|$)/ig, '$1<a href="$2" target="_blank">$2</a>$4');
};

called using prepareHtml(item.title)

Any idea how I can do this ? I've worked out regex to match the # and 5 digits is ^#([0-9]{5}) but I'm not sure how to implement this in the function.

Thanks

Rocket
  • 1,065
  • 2
  • 21
  • 44

1 Answers1

1

Looks to me that the pattern & replace string can be simplified a bit.

function urls2links(s)
{
    
return s.replace(/(^|[\s>])(www\.)/gi, '$1http://$2')
        .replace(/\b(((https?|ftps?):\/{2})(\S+?))(?=&quot;|&lt;|&gt;|[\s<>\"]|$)/ig, '<a href="$1" target="_blank">$1</a>');
};

var str = 'blah http://192.168.0.1/localsite/testschool/search.php?id=#12345 \nblah www.foo.com/bar/&quot; blah';

console.log('--\n-- BEFORE\n--');
console.log(str);
console.log('--\n-- AFTER\n--');
console.log(urls2links(str));

Although I'm not too sure about needing to include the character entities |&quot;|&lt;|&gt; in the lookahead.
But I'm guessing you also deal with encoded strings.

LukStorms
  • 28,916
  • 5
  • 31
  • 45