使用JavaScript代码实现URL获取#号后的值

javascript中,我编写了一个示例代码以从任何URL调用URL片段的“#”之后获取值。

使用“lastIndexOf”和“slice”获取它。

使用JavaScript代码实现URL获取#号后的值

获取“#”后的值

要获取“#”后的值,

1. 获取由“lastIndexOf”指定的字符串的最后一个索引

2. 获取不包括“#”的“slice”。

const url = 'https://www.ciyawang.com//#foo';

const last = url.lastIndexOf('#'); // 获取指定字符串的最后一个索引

console.log(last); // 26

console.log(url.slice(last)); // #foo

const hash = url.slice(last + 1); // 检索,但“#”除外

console.log(hash); // 'foo'

如果“#”不存在,则返回“-1”,因此将获取所有“URL”。

const url = 'https://www.ciyawang.com/foo';

const last = url.lastIndexOf('#'); // 获取指定字符串的最后一个索引
console.log(last); // -1

const hash = url.slice(last + 1); // 检索,但“#”除外
console.log(hash); // https://mebee.info/foo

如果您不想执行它,请按如下方式指定条件。

const url = 'https://www.ciyawang.com/foo';

const last = url.lastIndexOf('#'); // 获取指定字符串的最后一个索引
console.log(last); // -1

if(last !== -1){

  const hash = url.slice(last + 1); // 不执行
  console.log(hash); // 不执行

}

location.hash

如果它是一个可信的 URL,也可以使用“location.hash”来获取它。

console.log(location.hash); // #foo

const hash = location.hash.slice(1); // 检索,但“#”除外

console.log(hash); // 'foo'


最后编辑于:2023/03/10作者: 烽烟无限