Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove URL from a string completely in Javascript?

I have a string that may contain several url links (http or https). I need a script that would remove all those URLs from the string completely and return that same string without them.

I 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 keeps the link.

How to write the right regex that it would remove everything that follows http and also detect several links in the string?

Thank you so much!

like image 500
Aerodynamika Avatar asked May 09 '14 17:05

Aerodynamika


People also ask

How do you remove URL from text?

To remove a hyperlink but keep the text, right-click the hyperlink and click Remove Hyperlink. To remove the hyperlink completely, select it and then press Delete.

How do I remove http and www from URL?

To remove http:// or https:// from a url, call the replace() method with the following regular expression - /^https?:\/\// and an empty string as parameters. The replace method will return a new string, where the http:// part is removed. Copied!

How do I remove something from a string in JavaScript?

To remove a character from a string, use string replace() and regular expression. This combination is used to remove all occurrences of the particular character, unlike the previous function. A regular expression is used instead of a string along with global property.


1 Answers

You can use this regex:

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

This regex matches and removes any URL that starts with http:// or https:// or ftp:// and matches up to next space character OR end of input. [\n\S]+ will match across multi lines as well.

like image 190
anubhava Avatar answered Sep 19 '22 08:09

anubhava