0

我有一个网址如下

localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765

我使用 url 模块来解析下面路径名的 url 是代码

var url=require('url').parse('http://localhost:1340/promotionDetails/pwd1/pwd2?  promotion_id=PROM008765', true).pathname
console.log(url);

我得到的输出是

/promotionDetails/pwd1/pwd2

我使用 split 函数从路径中获取 pwd1 和 pwd2。我想知道是否有任何其他方法可以在不使用 split 函数的情况下获取 pwd1 和 pwd2。任何帮助都会非常有帮助。

4

2 回答 2

1

您可以使用正则表达式来获取 url 目录而不使用拆分。

var myurl = "localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765";
var match = myurl.match(/[^/?]*[^/?]/g);
/* matches everything between / or ?
[ 'localhost:1340',
  'promotionDetails',
  'pwd1',
  'pwd2',
  'promotion_id=PROM008765' ]
*/
console.log(match[2]);//pwd1
console.log(match[3]);//pwd2
于 2013-03-11T18:58:54.707 回答
0

更新 2019 ES6 答案:

您可以使用正则表达式来获取 url 目录而不使用拆分。

const myurl = "localhost:1340/promotionDetails/pwd1/pwd2?promotion_id=PROM008765";     
const filteredURL = myurl.match(/[^/?]*[^/?]/g).filter((urlParts) => {
    return urlParts !== 'promotionDetails' && urlParts !== 'localhost:1340'
})

const [pwd1, pwd2] = filteredURL;

console.log(pwd1)
console.log(pwd2)
于 2019-06-28T10:19:33.617 回答