Removing hash in my anchors

I am using this piece of code to display the index value of my loop slides at the end of the current url.

 var index = 0, hash = window.location.hash;
        if (hash) {
            index = /\d+/.exec(hash)[0];
            index = (parseInt(index) || 1) - 1; // slides are zero-based
        }

      

I want to remove the ' # ' in front of the value. How can I change this code?

+3


source to share


2 answers


So you are trying to remove the hash from the string:

hash.replace(/#/, '')

      



var hash = "url.com/#3"
document.getElementById("newUrl").innerHTML = hash.replace(/#/, '');
      

<div id="newUrl"></div>
      

Run codeHide result


@SmokeyPHP below indicates that I used a regex for this, but you can equally replace the string parameter: hash.replace('#', '')

+3


source


You can use the match function to print the hash in front and return the numbers. for example

var hash = '#12'
var index = hash.match(/#(\d+)/)
if (hash.length) index = index[1] - 1

      

To integrate with your code

 var index = 0, hash = window.location.hash;
 if (hash) {
   index = hash.match(/#(\d+)/)
   index = (index.length ? index[1] - 1: 0); // slides are zero-based
 }

      



If you want to output the number from the end of the url without a hash try this

window.location.href.match(/\/(\d+)(?:$|\?)/)

      

This means that the digit (s) is / is the last element at the end of the URL, with the option? for url vars

0


source







All Articles