斜线后如何获取网址参数

时间:2019-04-13 03:04:36

标签: javascript node.js

我有一个URL“ https://www.example.com/username”,我想从URL中提取用户名。例如'https://www.facebook.com/david'

3 个答案:

答案 0 :(得分:1)

 let href = "https://www.facebook.com/david"; 
// let href = "https://www.facebook.com/david"; // Current window url; 

// Creating URL object
let url = new URL(href);

console.log(url.pathname.substring(1));  // David

// If you looking for parameters after ? 
let exampleUrl = "https://www.facebook.com?name=david";
let paramUrl = new URL(exampleUrl);

console.log(paramUrl.searchParams.get("name"));   // david or null if not exist

答案 1 :(得分:0)

在node.js中,您应该使用url module

const Url = require('url');
console.log(new Url('https://www.facebook.com/david').pathname);
// 'david'

答案 2 :(得分:0)

您可以使用URL API,如果要摆脱领先的/,可以在从网址中提取substring后使用pathname

let url = `https://www.example.com/username`
let url2 = `https://www.example.com/username/somevalue`

let parsed = (url)=> {
   let urlParsed = new URL(url)
   return urlParsed.pathname.substring(1)
}

console.log(parsed(url))
console.log(parsed(url2))