10

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?

2
  • 4
    Why do you need to know the index of it? Just use the .match() function to test if the regexp matches? Commented Jun 1, 2016 at 15:16
  • Can't you just test what's in window.location.hash? Commented Jun 1, 2016 at 15:17

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the detailed explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.