Javascript: indexOf with Regular Expression

倖福魔咒の 提交于 2019-11-29 22:15:02

问题


How can I check whether the page url contains a '#' character plus some random digits

e.g. www.google.de/#1234

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

Does indexOf support Regular Expressions?


回答1:


Use String.prototype.search to get the index of a regex:

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

And RegExp.prototype.test if used for boolean checks:

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

The regex used for these examples are /#\d+$/ which will match literal # followed by 1 or more digits at the end of the string.

As pointed out in the comments you might just want to check location.hash:

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

/^#\d+$/ will match a hash that contains 1 or more digits and nothing else.



来源:https://stackoverflow.com/questions/37572652/javascript-indexof-with-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!