Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex for getting string before question mark if present

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?

like image 245
Anonymous Avatar asked Dec 19 '14 11:12

Anonymous


People also ask

How do you match a question mark in regex?

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.

How do you match something before a word in regex?

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 .

What is question mark in regex JavaScript?

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.

How do you check if a string contains a regex JavaScript?

If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() .


2 Answers

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".

Tests

example.com/#test                     -> "#test"
example.com/#test?params=something    -> "#test"
example.com/foo#test                  -> "#test"
example.com                           -> ""
like image 135
James Donnelly Avatar answered Sep 19 '22 01:09

James Donnelly


^(.*?)(?=\?|$)

You can try this.See demo.

https://regex101.com/r/vN3sH3/25

like image 36
vks Avatar answered Sep 20 '22 01:09

vks