javascript - 使用 Javascript 从 URL 中删除子目录
问题描述
我想从 URL ( https://testing.com/sg/features/ ) 中删除“sg”子目录,从而得到 ( https://testing.com/features/ )。
假设我的 window.location.href 是https://testing.com/sg/features/,我需要编辑并从中删除“sg”子目录,然后将其放入新位置而不对其进行硬编码。这意味着它将动态获取 URL,然后转到没有“sg”的位置(https://testing.com/features/)。
var url = 'https://testing.com/sg/features/';
var x = url.split('/');
console.log(x[3]); //result: sg
我只能从 URL 中获取 sg,但不知道如何删除它。
解决方案
我想说最好的方法是用'/'分割,寻找一个正是你要删除的字符串的部分,然后在忽略匹配项的同时重新组合新字符串。此代码删除字符串中的每个 /sg/
let thisLocation = "https://testing.com/sg/features/";
let splitLoc = thisLocation.split('/');
let newLocation = "";
for (let i = 0; i < splitLoc.length; i++){
if (splitLoc[i] !== "sg")
newLocation += splitLoc[i] + '/';
}
newLocation = newLocation.substring(0, newLocation.length - 1);
您还可以在查找“/sg/”时执行全局 .replace。你的选择
推荐阅读
- winforms - 用于证明我可以使用 NTLM 进行身份验证的表单应用程序
- python - 从动态创建的输入中获取输入
- amazon-ec2 - 让 wkhtmltoimage 在 Amazon Linux / Ruby on Rails 上工作的问题
- fullcalendar - FullCalendar - 如何删除小时,只有工作日?
- google-cloud-platform - 无法访问服务
- python - 无法使用 pipenv 安装频道(django)
- swift - NSAttributedStringKey.foregroundColor 不起作用
- excel - 在 Excel 中,如何从按等级排序的两个“向量”中添加值?
- c - C中的指针和二维数组
- ios - 在 iOS 上在线验证非消耗性应用内购买收据的正确工作流程?