删除我的锚点中的哈希值

时间:2015-05-14 19:50:16

标签: javascript jquery

我使用这段代码在当前网址末尾显示我的循环幻灯片的索引值。

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

我想删除' '在价值之前。我该如何修改此代码?

2 个答案:

答案 0 :(得分:3)

所以你试图从字符串中删除哈希:

hash.replace(/#/, '')

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

下面的@SmokeyPHP指出我使用正则表达式执行此操作,但您可以同样替换字符串参数:hash.replace('#', '')

答案 1 :(得分:0)

您可以使用匹配函数从前面拉出散列并返回数字。例如

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

与您的代码集成

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

如果您想在没有哈希值的情况下从网址末尾拉出一个数字,请尝试以下

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

这确保数字是网址末尾的最后一项,可选吗?为url vars