【问题标题】:Shrinking URL in JavaScript [duplicate]在 JavaScript 中缩小 URL [重复]
【发布时间】:2021-06-16 13:08:42
【问题描述】:

我们如何在 JavaScript 中缩小 URL:

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

https://stackoverflow.com/questions/ask

预期输出:

https://stackoverflow.com

感谢您的宝贵时间,

解决方案: 我已经使用正则表达式来缩小网址

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 中仅显示您想要的部分

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 我已经尝试使用字符串的长度进行缩小并使用字母进行缩小,但是,如果有任何方法可以使用字符串来缩小它(比如在 .com 之后),它可能会更好,或者如果你有什么建议我也会试试的,

标签: javascript function frontend web-frontend


【解决方案1】:

基于这个answer,你可以做一些这样的事情

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

【讨论】:

    【解决方案2】:

    可以使用URL类解析URL,得到origin

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

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2010-10-27
      • 2021-04-24
      • 1970-01-01
      • 2011-05-03
      • 2012-10-23
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多