【问题标题】:Javascript: indexOf with Regular ExpressionJavascript:带有正则表达式的 indexOf
【发布时间】:2016-06-01 15:15:50
【问题描述】:

如何检查页面url是否包含'#'字符加上一些随机数字

例如www.google.de/#1234

if( window.location.href.indexOf('#') > 0 ){
  alert('true');
}

indexOf 是否支持正则表达式?

【问题讨论】:

  • 为什么需要知道它的索引?只需使用.match() 函数来测试正则表达式是否匹配?
  • 你不能只测试window.location.hash中的内容吗?

标签: javascript regex indexof


【解决方案1】:

使用String.prototype.search 获取正则表达式的索引:

'https://example.com/#1234'.search(/#\d+$/); // 20

如果用于布尔检查,RegExp.prototype.test

/#\d+$/.test('https://example.com/#1234'); // true

用于这些示例的正则表达式是 /#\d+$/,它将匹配文字 #,后跟字符串末尾的 1 个或多个数字。

正如 cmets 中所指出的,您可能只想检查location.hash

/^#\d+$/.test(location.hash);

/^#\d+$/ 将匹配包含 1 个或多个数字且仅包含其他内容的哈希。

【讨论】:

  • 非常感谢您的详细解释。
猜你喜欢
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 2021-01-07
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
相关资源
最近更新 更多