Re-express Javascript to get the line before the question mark, if present

Do I have this line: #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. A nested function returns an error if a question mark is not found. The goal is to always return #test if there are additional options or not. How to create a regex that returns this?

+5
source share
5 answers

Is this line direct from the current page URL?

If so, you can simply use:

 window.location.hash.split('?')[0] 

If you visit http://example.com/#test?params=something , the above code will return "#test".

Test

 example.com/#test -> "#test" example.com/#test?params=something -> "#test" example.com/foo#test -> "#test" example.com -> "" 
+4
source
 ^(.*?)(?=\?|$) 

You can try this. Watch the demo.

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

+2
source

You can use:

 var regExp = /^([^?]+)/; 

Will this always return a string before the first ? whether present or not ? at the entrance.

RegEx Demo

+1
source

A simple alternative:

 hash = str.substr(0, (str + "?").indexOf("?")); 
+1
source

Either I'm missing something, or just:

  ^#\w+ 

It seems to need to do the work for both ( this and this )

0
source

Source: https://habr.com/ru/post/1209537/


All Articles