'how to display url in text without site name, without slash, merged?

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"?



Solution 1:[1]

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))

Solution 2:[2]

You could do something like:

const url = "sitename.site/job/cvs/index.html"
const parts = url.split("/");
parts.shift();
parts.pop();
const res = parts.join('');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 user13057318