How can I effectively add a "path" to the middle of an URL in JavaScript?
I want to add embed to an URL, so the URL will end up looking like this
?
Cheers
How can I effectively add a "path" to the middle of an URL in JavaScript?
I want to add embed to an URL, so the URL https://blog./post/123
will end up looking like this https://blog./embed/post/123
?
Cheers
Share Improve this question asked Jun 24, 2018 at 20:13 Emil Devantie BrockdorffEmil Devantie Brockdorff 4,95413 gold badges61 silver badges79 bronze badges 2- 1 You must have read this before How to Ask and minimal reproducible example – Asons Commented Jun 24, 2018 at 20:15
- 1 I totally get this question just by the title, don't know where all the hate is ing from – elad silver Commented Jun 11, 2021 at 20:31
4 Answers
Reset to default 1You can create an <a>
and set the href
property. Then prepend embed
to the pathname and use toString() to get the whole URL.
let element = document.createElement('a');
element.href = 'https://blog./post/123';
element.pathname = 'embed' + element.pathname;
console.log(element.toString());
You can do this, if the path is just a string
var path = "https://blog./post/123";
var withEmbed = path.replace(/\/post\//,'/embed/post/');
console.log(withEmbed);
You can use the location API.
https://developer.mozilla/en-US/docs/Web/API/Location
function addEmbed(location) {
return location.protocol + '//' + location.host +
'/embed' + location.pathname;
}
var url = document.createElement('a');
url.href = 'https://blog./post/123';
var embed = addEmbed(url);
console.log(embed); // "https://blog./embed/post/123"
Example: https://codepen.io/anon/pen/wXxvaq
The way i would do it, is to pass by ref/value the original URL and the text you wan to add, into a function. It then removes the "https://" (if necessary), splits the url at the first "/" and saves each part as a var. Finally it puts it all back together and outputs it to a
on the html page. This doesnt have to be outputted in this way, it could be saved as a global variable and then used in a link (but i didn't know what your plan was so i outputted it) :)
function addToURL(URL, add) {
URL = URL.replace(/(^\w+:|^)\/\//, '');
var part1 = URL.substring(0, URL.indexOf("/") + 1);
var part2 = URL.substring(URL.indexOf("/"), URL.length);
var result = "https://" + part1 + add + part2;
document.getElementById("demo").innerHTML = result;
}
Here's the example I made: https://codepen.io/anon/pen/RJBwZp
Hope this helps :P