javascript - 使用 replace 和 pathArray[0],我似乎是在添加而不是用我的 JavaScript 替换
问题描述
我制作了一个简单的浏览器扩展,并有一个 manifest.json 文件,该文件通过 background.js 文件运行到我的 JavaScript 文件中,其中包含此代码
var l=location;
var str2='/edit';
var pathArray = l.pathname.split('/');
var secondLevelLocation = pathArray[1];
pathArray[1] = 'node';
l.href=l.origin.replace(l.origin, pathArray[1])+l.pathname.concat(str2);
但不是替换 pathArray[1],而是添加到 url。
例如,脚本正在采取:https://mywebiste.com/items/1234;并替换为:https ://mywebiste.com/items/node/items/1234/edit
但是,预期的输出是:https ://mywebiste.com/node/1234/edit
更新
在对不正确的数组编号发表评论后,我更新了我的脚本,但它自然不能解决问题。
解决方案
所以,如果你的 url 是这样的:https://mywebiste.com/items/1234
并且你用 分割它/
,那么你就会有这样的东西:["https:", "", "mywebiste.com", "items", "1234"]
如您所见,第三个位置是items
您需要的,因此您可以这样做:
yourUrl.replace(yourUrl.split('/')[3], 'node').concat('/edit');
随意使用'node'和'/edit'作为变量。
希望它可以帮助你。
编辑:
我能想到的最简单的方法:
let href = location.origin + location.pathname.replace('items', 'node').concat('/edit')
推荐阅读
- python-3.x - 为什么在 Tkinter 中创建小部件时,对象和方法之间需要一个空格?
- tomcat - 在 Tomcat 上部署 Eureka 客户端失败 - 无法启动 bean“eurekaAutoServiceRegistration”:没有为范围名称“刷新”注册范围
- android - 如何将数据绑定变量作为 xml 属性传递给自定义视图
- typescript - TypeScript 中的自定义 keyValue 类型
- c++ - 具有模板类型的函数的显式(完全)特化
- node.js - aws lambda 和 promise-mysql
- android - 如何更新 Firestore 中地图数组中的元素?
- github - 为什么查询对 sample_commits 有效,但对公共 github_repos 数据集中的提交无效?
- windows - 在将参数传递给 PS 文件时,如何使用 invoke-command 从 Windows 命令行运行 PS 文件?
- bash - 如何自动解决 git rebase 中的所有冲突,“git add .”