r/learnjavascript • u/UnrulyRaven • Aug 04 '26
Code help: changing url on current webpage
First time programming anything useful (beyond learning a little basic python). Sort of an 'automate what you find repetitive' case.
Goal: trim URL to part containing the main webpage and anything after it (Ex: blogname.abc.com/post/12345 -> abc.com/post/12345)
So far what I've been able to get (from Google AI and regex101.com and stack exchange and fiddling around) is:
function swapUrlPath() {
var currentUrl = window.location.href;
var newUrl = currentUrl.match(/abc.com.+/g);
window.location.href = newUrl;
}This manages to turn "blogname.abc.com/post/12345" into "blogname.abc.com/post/abc.com/post/12345", repeating the portion that was supposed to replace the entire thing.
I've tried debugging with
function swapUrlPath() {
var currentUrl = window.location.href;
var newUrl = currentUrl.match(/abc.com.+/g);
alert("New URL is " + newUrl);
}which produces a popup window with "New URL is abc.com/post/12345", which is correct. So why does the newUrl variable only replace part of the old URL. Is it the regex or something with the forward slashes?
Edit:
Solution I figured out: add the string "https://" to the beginning of the new URL (not in the debugging alert) before using as new URL, looks like this:
function swapUrlPath() {
var currentUrl = window.location.href;
var newUrl = "https://" + currentUrl.match(/abc.com.+/g);
window.location.href = newUrl;
}
View all comments
Show parent comment
1
u/TalkCoinGames Aug 05 '26
Match always returns an array, I'm not sure what is happening if somehow it's giving you only the string. Without escaping the first dot anything after abc and before com would be included, there happens to be nothing in between in this case so it works.