简体   繁体   中英

How to remove the "#" symbol from the URL

I have a link that takes me to another section of the same page like this:

<a class="nav-link" href="#about">About</a>

that takes me here:

<section class="page-section bg-primary" id="about"></section>

Whenever I click on the link, the search bar shows up as http://mywebsite.com/home/#about . I want it so that whenever an anchor link is clicked it takes me to that section in the page but instead of having a hash in the search bar I want it nice and clean with / instead of # , like http://mywebsite.com/home/about . How can I achieve this?

This may be done using a popstate event handler and history.replaceState .

Not sure if this is necessarily the best or even a viable solution.

window.addEventListener(`popstate`, handle);

function handle(evt) {
  if (location.hash) {
    history.replaceState(null, ``, location.pathname);
  }
}

It can't be demonstrated in a snippet here, so check this stackblitz .

这应该这样做: location.origin+location.pathname

You can listen for the hash change and replace the search bar's # with a / .

Here's some (independent) code:

let first = true; // so we know whether to replace or add
window.addEventListener("hashchange", () => {
    if(first)
        return (
            history.pushState(null, null, location.href.replace("#", "/")),
            first = false
        );
    const all = location.href.split("/"); // if we replaced the last one with `/`, we don't want to add on to it
    all[all.length - 1] = location.hash.slice(1); // slice(1) gets rid of the `#`
    history.pushState(null, null, all.join("/"));
});

This exhibits all the normal traits of an anchor link, where when you click on a link the page's history is pushed instead of replaced. I think this is also what you wanted from what I could understand in your question.

This behavior is part of HTML. In my opinion is that good to have hash routes. But i dont know your issue. How ever. A simple solution would be to listen to the anchors and remove the # after clicking.

const anchors = document.querySelectorAll(".nav-link");
anchors.forEach(a => {
  a.addEventListener("click", () => {
    console.log("remove # from: ", window.location.href)
    window.location.href.split('#')[0]
    return false;
  })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM