How to remove a URL from a string completely in Javascript?

I have a string that can contain multiple urls (http or https). I need a script that will completely remove all these URLs from the string and return the same string without them.

I have tried so far:

var url = "and I said http://fdsadfs.com/dasfsdadf/afsdasf.html"; var protomatch = /(https?|ftp):\/\//; // NB: not '.*' var b = url.replace(protomatch, ''); console.log(b); 

but this only removes the http part and saves the link.

How to write the correct regular expression to delete everything that follows http, and also to find some links in a line?

Thank you very much!

+6
source share
2 answers

You can use this regex:

 var b = url.replace(/(?:https?|ftp):\/\/[\n\S]+/g, ''); //=> and I said 

This regular expression matches and removes any URL starting with http:// or https:// or ftp:// and matches the next space or end of input. [\n\S]+ will match multiple lines as well.

+19
source

Have you been looking for a regular expression for the URL parser? This question contains some comprehensive answers. Getting URL parts (Regex)

However, if you want something much simpler (and maybe not so perfect), you should remember the entire url string, not just the protocol.

Something like /(https?|ftp):\/\/[\.[a-zA-Z0-9\/\-]+/ should work better. Note that the added half parses the remainder of the URL after the protocol.

+1
source

All Articles