我如何检查网页 URL 是否包含 '#' 字符加上一些随机数字
例如:www.google.de/#1234
例如:www.google.de/#1234
if( window.location.href.indexOf('#') > 0 ){
alert('true');
}
indexOf支持正则表达式吗?
if( window.location.href.indexOf('#') > 0 ){
alert('true');
}
indexOf支持正则表达式吗?
使用String.prototype.search
方法获取正则表达式的索引:
'https://example.com/#1234'.search(/#\d+$/); // 20
如果用于布尔检查,则使用 RegExp.prototype.test
方法:
/#\d+$/.test('https://example.com/#1234'); // true
这些示例使用的正则表达式是/#\d+$/
,它将匹配字符串末尾的字面值#
后跟1个或多个数字。
正如评论中指出的那样,您可能只想检查location.hash
:
/^#\d+$/.test(location.hash);
/^#\d+$/
将匹配只包含一个或多个数字的哈希标记,没有其他内容。
.match()
函数测试正则表达式是否匹配即可。 - Barmarwindow.location.hash
中的内容吗? - Barmar