I have this string: #test
or #test?params=something
var regExp = /(^.*)?\?/;
var matches = regExp.exec($(this).data('target'));
var target = matches[1];
console.log(target);
I always need to get only #test.
The function I pasted returns an error if no question mark is found. The goal is to always return #test
whether there are additional params or not. How do I make a regex that returns this?
But if you want to search a question mark, you need to “escape” the regex interpretation of the question mark. You accomplish this by putting a backslash just before the quesetion mark, like this: \? If you want to match the period character, escape it by adding a backslash before it.
Take this regular expression: /^[^abc]/ . This will match any single character at the beginning of a string, except a, b, or *c. If you add a * after it – /^[^abc]*/ – the regular expression will continue to add each subsequent character to the result, until it meets either an a , or b , or c .
The question mark gives the regex engine two choices: try to match the part the question mark applies to, or do not try to match it. The engine always tries to match that part. Only if this causes the entire regular expression to fail, will the engine try ignoring the part the question mark applies to.
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() .
Is that string direct from the current page's URL?
If so, you can simply use:
window.location.hash.split('?')[0]
If you're visiting http://example.com/#test?params=something, the above code will return "#test".
example.com/#test -> "#test"
example.com/#test?params=something -> "#test"
example.com/foo#test -> "#test"
example.com -> ""
^(.*?)(?=\?|$)
You can try this.See demo.
https://regex101.com/r/vN3sH3/25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With