首页 > 解决方案 > 使用 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

更新

在对不正确的数组编号发表评论后,我更新了我的脚本,但它自然不能解决问题。

标签: javascript

解决方案


所以,如果你的 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')


推荐阅读