I'm writing a function that checks for HTTP links and replaces them with anchor tags if they exist. If there is a YouTube URL, it replaces it with an iframe. I'm having trouble finishing it since I can't figure out how to just add an anchor for those URLs that aren't YouTube URLs.
Here's the functions
export const renderLinkWithText = (text = '') => {
// eslint-disable-next-line
const replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim
const newText = text.replace(replacePattern1, '<a class="anchor_link" target="_blank" href="$1">$1</a> ')
return newText.replace(/\n\r?/g, '<br />').replace(/(?:https:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?.*v=)?(\w+)/g, '<iframe width="100%" height="350px" src="https://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>')
}
You would want to include a negative lookahead in your 1st pattern with which to exclude youtube urls. Something along the lines of:
(?!(www.)?(youtube\.com|youtu\.be))
The entire pattern would than become:
(\b(https?|ftp):\/\/(?!(www.)?(youtube\.com|youtu\.be))[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])
Edit: I've corrected the initial answer, you test your regular expressions online. https://regex101.com/ for one accepts the above.