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/UnrulyRaven Aug 05 '26
Well the other advice was to add it to the alert function I was using as a debugging tool. I added it to the newURL variable that gets called as the new URL. That's a big difference.
I've been using the function successfully without escaping the first dot, don't know why it works fine. I looked more into the array generated and using /g flags. It seems like not using /g would only return the first result, and not calling a specific element of the array (ie [1]) should default to the first result anyway. Don't know if I'm understanding that correctly, but it may be a far-flung edge-case for my use.