zlDeath
zlDeath

Reputation: 13

Regex or Split function

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

Answers (1)

Tom
Tom

Reputation: 9127

I'd handle this like so:

  1. write a function that can identify a URL in a string, that returns the URL
  2. use String.replace on the original string to remove the URL that was found

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

Related Questions