删除url javascript中域名和http之后的所有内容



我在javascript变量中有完整的url,我想将其剥离为裸url。

例如:

https://www.google.com/hello/hi.php,http://youtube.com

down to:

www.google.com, youtube.com

我如何在javascript中做到这一点?

感谢

这是不类似于其他链接,因为我这样做一个chrome扩展内,因此唯一的方法来获得url是使用chrome扩展api,只提供完整的url。因此,我需要删除完整的url

你可以试试:

//([^/,s]+.[^/,s]+?)(?=/|,|s|$|?|#)

Regex live here.


实时JavaScript示例:

var regex = ///([^/,s]+.[^/,s]+?)(?=/|,|s|$|?|#)/g;
var input = "https://www.google.com/hello/hi.php, http://youtube.com,"
          + "http://test.net#jump or http://google.com?q=test";
while (match = regex.exec(input)) {
    document.write(match[1] + "<br/>");
};


希望有所帮助

使用全局window.location.hostname变量,它将为您提供这些信息。

虽然像其他答案建议的那样使用正则表达式进行解析是可能的,但更好的方法是使用URL()对象/API (docs)。

const a = "https://www.google.com/hello/hi.php";
const hostname = new URL(a).hostname; // "www.google.com"

除了可以说是"更干净"之外,另一个优点是,如果底层解析逻辑不正确,它是浏览器中的一个(潜在的安全)错误,而不是您的代码,并且很可能无需您的努力就可以修复。