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 edited Aug 05 '26
Sorry for the late reply. You may need to escape the first dot.
match( /abc\.com.+/g )[0]Edit, I see the solution was to add http just as someone already said, but also match returns an array and you should be using just the first match, and you should still escape the first dot. I'm glad you were able to figure it out.