javascript 如何在Javascript中完全从字符串中删除URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23571013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove URL from a string completely in Javascript?
提问by Aerodynamika
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.
我有一个字符串,其中可能包含多个 url 链接(http 或 https)。我需要一个脚本来完全从字符串中删除所有这些 URL,并在没有它们的情况下返回相同的字符串。
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.
但这只会删除 http 部分并保留链接。
How to write the right regex that it would remove everything that follows http and also detect several links in the string?
如何编写正确的正则表达式以删除 http 后面的所有内容并检测字符串中的多个链接?
Thank you so much!
太感谢了!
回答by anubhava
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.
此正则表达式匹配并删除以http://
orhttps://
或 or开头ftp://
并匹配到下一个空格字符 OR 输入结尾的任何 URL 。[\n\S]+
也将匹配多行。
回答by Kyle
Did you search for a url parser regex? This question has a few comprehensive answers Getting parts of a URL (Regex)
您是否搜索过 url 解析器正则表达式?这个问题有一些综合答案获取 URL 的一部分(正则表达式)
That said, if you want something much simpler (and maybe not as perfect), you should remember to capture the entire url string and not just the protocol.
也就是说,如果你想要更简单的东西(也许不那么完美),你应该记住捕获整个 url 字符串而不仅仅是协议。
Something like
/(https?|ftp):\/\/[\.[a-zA-Z0-9\/\-]+/
should work better. Notice that the added half parses the rest of the URL after the protocol.
像这样的东西
/(https?|ftp):\/\/[\.[a-zA-Z0-9\/\-]+/
应该工作得更好。请注意,添加的一半解析协议之后的 URL 的其余部分。