2

I'm developing a community site. When a user posts a comment that contains a URL, I want to enclose that url in an <a> tag.

Input

Hello. Please take a look at this video.
https://example.com

Output

Hello. Please take a look at this video.
<a href="https://example.com">https://example.com</a>

Code

I would like to know what I should put in regex and sanitizer below.

const el = document.getElementById('comment')
const commentText = `Hello. Please take a look at this video.\nhttps://example.com`

el.innerHTML = commentText.replace(/regex/g, function(match){
    const sanitizedText = sanitizer(match)
    return `<a href="${sanitizedText}">${sanitizedText}</a>`
})

Or if there is a better way, please let me know.

user776490
  • 115
  • 2
  • 8

1 Answers1

0

Try this regex, which allows both http and https protocols whilst preserving the path.

var res = "https://www.google.com/search".replace(new RegExp('^(https?:\\/\\/)?'+
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+
    '((\\d{1,3}\\.){3}\\d{1,3}))'+
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
    '(\\?[;&a-z\\d%_.~+=-]*)?'+
    '(\\#[-a-z\\d_]*)?$','i'), function(match){
    const sanitizedText = match.slice(8);
    return `<a href="https://${sanitizedText}">https://${sanitizedText}</a>`
})
document.write(res);
Spectric
  • 30,714
  • 6
  • 20
  • 43