Reputation: 13
Hello good afternoon everyone!
I'm trying to make a regex or splice to remove the link from a sentence and the sentence from the link.
So far I have achieved this here:
function replaceURL(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
return text.replace(exp, "$1");
}
console.log(replaceURL1("Hi, watch my video https://youtu.be/urllink"))
I wanted the result like this:
let phrase = "Hi, watch my video";
let url = "https://youtu.be/urllink";
Could someone help me? I don't understand regex very well ... If you succeed with split how would it be?
Thanks ️!
Upvotes: 0
Views: 40
Reputation: 9127
I'd handle this like so:
URLs can be very hard to write regexes for, because the spec governing URLs supports an enormous number of variations as well as the huge UTF-16 charset. You may be able to avoid all of that complexity by assuming that every URL will start with "http:" or "https:".
function getUrlFromString( string ) {
return string.match(/ *(https?:[^ ]+)/i)[0]
}
function separateUrlAndStatement( string ) {
let url = getUrlFromString(string)
let statement = string.replace(url, '')
return { url, statement }
}
Upvotes: 2