我已经降低了stackoverflow的速度,由于某种原因,这个问题根本无法以足够清晰的方式回答我。
我的网址路径为www.thisurl.com/this/url/is/generic%877948
我想仅控制台控制台url,以除去其中的查询部分,所以我得到的只是:www.thisurl.com。
我尝试了以下操作:
var pathtotrim = location.href.split('/').pop();
document.write(pathtotrim);
console.log("hello", pathtotrim);
但是,这会剪裁掉url的开头,让我留下/ this / url / is / generic%877948。
本质上是与我想要的相反。我如何修剪网址的查询部分以进行控制台记录..请!!! ???
答案 0 :(得分:0)
尝试一下:
var pathtotrim = location.href.split('/')[0];
这将在/
上拆分字符串,但将采用第一段(在您的情况下为www.x.com)
编辑:
像Leilo Faieta所说的,location.host
或location.hostname
会更快。
答案 1 :(得分:0)
var pathtotrim = "www.thisurl.com/this/url/is/generic%877948".split('/')[0];
document.write(pathtotrim);
console.log("hello", pathtotrim);
答案 2 :(得分:0)
无需操纵字符串:您可以只使用location.host
或location.hostname.
这将为您提供网址的www部分。
在此网址上:
https://www.google.com/search?safe=off&source=hp&ei=P9SXW7_RO9CKmgWiybjIBA&q=location&oq=location&gs_l=psy-ab.3..0j0i131k1j0l8.269799.273393.0.273746.20.13.4.1.1.0.156.1198.8j4.13.0....0...1c.1.64.psy-ab..2.18.1341.6..35i39k1j0i10k1.98.Zbh8pzpSLkY
您将获得
www.google.com
如果您想让网址的所有第一部分都包括http协议
location.protocol + '//' + location.host
您将在相同的示例网址上获得
https://www.google.com
答案 3 :(得分:0)
let url = 'www.thisurl.com/this/url/is/generic%877948'
console.log(url.replace(/\/.*/g, ''));