给定一个完整的URI字符串,我只想返回协议和域名。例如:
sometodo("http://127.0.0.1:8000/hello/some/word1212/")
// return: http://127.0.0.1
sometodo("http://127.0.0.1:8000/hello/some/valorant_operator/")
// return: http://127.0.0.1
如何从字符串中删除第三个/
和以下信息?
如果它将是URL,那么就像处理URL一样处理它。无需解析/regex/substring,只需创建一个URL对象并访问其值即可。
https://developer.mozilla.org/en-US/docs/Web/API/URL
const url = new URL("http://127.0.0.1:8000/hello/some/word1212/");
let result = `${url.protocol}//${url.host}`;
sometodo("http://127.0.0.1:8000/hello/some/word1212/");
sometodo("http://127.0.0.1:8000/hello/some/valorant_operator/");
function sometodo(str) {
var output = str.match(/^(?:[^/]*/){3}/)[0];
console.log(output);
return output;
}