Javascript:indexOf with Regular Expression [英] Javascript: indexOf with Regular Expression
问题描述
如何检查网页网址是否包含#字符加上一些随机数字
How can I check whether the page url contains a '#' character plus some random digits
例如www.google.de/#1234
e.g. www.google.de/#1234
if( window.location.href.indexOf('#') > 0 ){
alert('true');
}
indexOf是否支持正则表达式?
Does indexOf support Regular Expressions?
推荐答案
使用 String.prototype.search
获取正则表达式的索引:
Use String.prototype.search
to get the index of a regex:
'https://example.com/#1234'.search(/#\d+$/); // 20
RegExp.prototype.test
如果用于布尔检查:
And RegExp.prototype.test
if used for boolean checks:
/#\d+$/.test('https://example.com/#1234'); // true
用于这些示例的正则表达式是 /#\d + $ /
,它将匹配文字#
,后跟字符串末尾的1位或更多位数。
The regex used for these examples are /#\d+$/
which will match literal #
followed by 1 or more digits at the end of the string.
正如评论中所指出的,您可能只想检查 location.hash
:
As pointed out in the comments you might just want to check location.hash
:
/^#\d+$/.test(location.hash);
/ ^#\d + $ /
将匹配包含1位或更多位数的哈希值。
/^#\d+$/
will match a hash that contains 1 or more digits and nothing else.
这篇关于Javascript:indexOf with Regular Expression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!