简体   繁体   中英

Using replace and pathArray[0], I seem to be adding rather than replacing with my JavaScript

I have made a simple browser extension and have a manifest.json file that runs through a background.js file into my JavaScript file, which has this code

 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);

But rather than replacing pathArray[1], it's adding to the url.

For example, the script is taking: https://mywebiste.com/items/1234 ; and replacing with: https://mywebiste.com/items/node/items/1234/edit

However, the intended output is: https://mywebiste.com/node/1234/edit

Updated

Following comments on incorrect array number, I've updated my script but naturally it doesn't fix the issue.

So, if you have your url like this: https://mywebiste.com/items/1234 and you split it by / , then you will have something like this: ["https:", "", "mywebiste.com", "items", "1234"]

as you see, the 3rd position is the items that you need, so you can do:

yourUrl.replace(yourUrl.split('/')[3], 'node').concat('/edit');

Feel free to use 'node' and '/edit' as variables as you did.

Hope it helps you.

EDIT:

The easiest way I can think:

let href = location.origin + location.pathname.replace('items', 'node').concat('/edit')

The simplest approach:

 // emulating window.location var l = { "href": "https://mywebiste.com/items/1234" }; console.log("Input:", l.href); console.log("Output:", l.href.replace(/items/i, "node") + "/edit");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM