如何删除除第一个以外的所有URL哈希?

时间:2019-05-12 17:13:08

标签: javascript jquery url hash

好吧,在我的网站上,我有一个常见问题解答,用户可以通过该常见问题解答访问特定的问题,例如:

https://example.com/faq#question-1

为此,我使用了Jquery,例如:

if (window.location.hash) {
    $(window.location.hash).open();
}

但是我希望如果用户在URL中输入多个哈希值,例如:

https://example.com/faq#question-1#question-2#question-3#question-n

除了第一个#question-1

之外的所有哈希都已从网址中删除

我该怎么做?

编辑: 如果用户类型为https://example.com/faq#question-1#question-2#question-3#question-n,则将URL更改为https://example.com/faq#question-1,以便只有第一个哈希出现在URL中,而FAQ仅读取一个哈希。

3 个答案:

答案 0 :(得分:1)

这应该为您工作

var str="https://example.com/faq#question-1#question-2#question-3#question-n";
var trimmedStr = str.split("#").slice(0,2).join("#");
console.log(trimmedStr);
    

这会删除第一个哈希之后的所有哈希。

答案 1 :(得分:1)

这可能像

var hash = window.location.hash;
var filtered_hash = '';
if(hash.length > 0){
  filtered_hash = '#' + hash.split("#")[1];
  window.location.hash = filtered_hash;
}

console.log(filtered_hash);

答案 2 :(得分:1)

您可以使用-

// clock.cpp : main project file.
using namespace std;
#include <iostream>
#include <cstdio>
#include <ctime>
int main() {
   int x = 0;
   std::clock_t start;
   double duration;
   start = std::clock();
   for (int i = 0; i <= 100000000; i++) {  
       x++;
       x--;
   }
   /* Your algorithm here  instead of the loop above */
   duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
   std::cout<<"printf: "<< duration <<'\n';
   char ch;
   cin >> ch;
}