【问题标题】:How to seperate link to get product info?如何分离链接以获取产品信息?
【发布时间】:2020-11-19 00:47:40
【问题描述】:

我想通过 javascript 链接获取产品详细信息。

产品名称始终位于“item-detail-page-”和“--”之间 产品价格始终在“--”和“-”之间

示例链接:

https://www.blabla.com/products/item-detail-page-proofice-paper--20-14554/1
https://www.blabla.com/products/item-detail-page-faber-pencil--100-145354/2
https://www.blabla.com/products/item-detail-page-led-lamp-xl--55-143555/1

我可以使用“var currentLocation = window.location;”获取页面的网址但是如何划分链接并获取这两个信息呢?

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 您需要在提供的示例中提取proofice-paperfaber-pencilled-lamp-xl。正确的?您能否将代码发布到您遇到问题的确切位置。

标签: javascript regex url


【解决方案1】:

你需要使用字符串的各种功能来实现它。请检查以下代码。

var url1 = 'https://www.blabla.com/products/item-detail-page-proofice-paper--20-14554/1'
var url2 = 'https://www.blabla.com/products/item-detail-page-faber-pencil--100-145354/2'
var url3 = 'https://www.blabla.com/products/item-detail-page-led-lamp-xl--55-143555/1'

function getProductInfo(url) {
    var urlComponent = url.split('/');
    var itemDetsils = urlComponent[urlComponent.length - 2];

    return {
        productName: itemDetsils.substring(17, itemDetsils.indexOf("--")),
        productprice: itemDetsils.substring(itemDetsils.indexOf("--") + 2, itemDetsils.lastIndexOf("-")),
    }
}


console.log(getProductInfo(url1));
console.log(getProductInfo(url2));
console.log(getProductInfo(url3));

【讨论】:

    【解决方案2】:
    const regex = /(?<=item-detail-page-)(.*)(?=--)/g
    window.location.pathname.match(regex)
    

    应该可靠地做你想做的事:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2012-05-28
      • 2015-12-09
      相关资源
      最近更新 更多