1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Get current page without query string

Discussion in 'JavaScript' started by energylevels, Jun 27, 2020.

  1. #1
    How do i modify this to return the current page without the query string

    document.write(location.href.split("/").slice(-1));
    Code (markup):

    SEMrush
     
    energylevels, Jun 27, 2020 IP
    SEMrush
  2. JEET

    JEET Notable Member

    Messages:
    3,760
    Likes Received:
    493
    Best Answers:
    19
    Trophy Points:
    235
    #2
    Try this, but this gets full URL, not just filename like your original function does.

    <script type="text/javascript">
    document.write( location.href.split("?").slice(0,1) );
    </script>
     
    JEET, Jun 27, 2020 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,636
    Likes Received:
    1,972
    Best Answers:
    249
    Trophy Points:
    515
    #3
    use .pathName insteaad of .href. I'd also suggest using substring instead of split/slice as it executes faster.

    
    location.pathName.substring(location.pathName.lastIndexOf('/') + 1);
    
    Code (markup):
    Should do the trick. You could also get the length to remove from the end of location.href via location.search, but that could still include the hash so you'd need that as well.

    Remember, window.location is an instance of Location. Hence all the properties of Location are available to you:

    https://developer.mozilla.org/en-US/docs/Web/API/Location

    It's already split into pathname, hash, search (query string), etc, etc.

    Location.pathName is also nice in that it already has the protocol stripped off.
     
    deathshadow, Jun 27, 2020 IP
    JEET likes this.
  4. energylevels

    energylevels Member

    Messages:
    9
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    38
    #4
    thanks for replies, I went with this:
    document.write(location.pathname.split("/").slice(-1));
    Code (markup):
     
    energylevels, Jun 28, 2020 IP
    JEET likes this.