我有一个URL“ https://www.example.com/username”,我想从URL中提取用户名。例如'https://www.facebook.com/david'
答案 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)