how to display url in text without site name, without slash, merged?
Example site url: sitename.site/job/cvs/index.html
How do I get the text: “jobcvs”?
Advertisement
Answer
I’m assuming that you want to be able to get the joined path of any URL. If this is the case you can use the URL api to get the pathname, split it on “/” and join everything except the file name back together and return the result. Below is what I’ve come up with. This could probably be reduced to a one-liner, but I’ve left it long form for readability.
function getJoinedPathname(url) { const urlObj = new URL(url); const pathnameSplit = urlObj.pathname.split('/') return pathnameSplit.reduce((a, b, index) => { if (index !== pathnameSplit.length - 1) return a + b; return a }) } console.log(getJoinedPathname('https://sitename.site/job/cvs/index.html')) console.log(getJoinedPathname('https://sitename.site/job/cvs/anotherpath/index.html')) console.log(getJoinedPathname('https://sitename.site/job/cvs/1/2/3/index.html')) console.log(getJoinedPathname('https://sitename.site/job/cvs/index.html?name=test')) console.log(getJoinedPathname('https://stackoverflow.com/questions/64055299/how-to-display-url-in-text-without-site-name-without-slash-merged')) console.log(getJoinedPathname(window.location.href))