首页 > 解决方案 > 在 JavaScript 中缩小 URL

问题描述

我们如何在 JavaScript 中缩小 URL:

例如,如果链接是这样的,则不应在 .com 之后扩展

https://stackoverflow.com/questions/ask

预期输出:

https://stackoverflow.com

谢谢你的时间,

解决方案:我使用 Regexp 来缩小 url

const yourUrl = {your url goes here}  
const reConstructUrl = new RegExp(
      [
        "^(https?:)//", // protocol
        "(([^:/?#]*)(?::([0-9]+))?)", // host (hostname and port)
         '(/{0,1}[^?#]*)', // pathname
         '(\\?[^#]*|)', // search
         '(#.*|)$' // hash
      ].join("")
    )
const matchedUrl = yourUrl.match(reConstructUrl);

现在您可以从 URL 中仅显示您想要的部分

标签: javascriptfunctionfrontendweb-frontend

解决方案


基于这个答案,你可以做这样的事情

const url = new URL('https://stackoverflow.com/questions/ask');
console.log(url.origin)


推荐阅读