6

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?

1
  • 1
    As rule of thumb - you should use direct string modification methods (like split, strpos, substring etc) instead of regex, when there's no specific need for regex. I would go with method suggested by James. Commented Dec 19, 2014 at 11:36

5 Answers 5

5

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                           -> ""
1
  • 1
    OP asked for a regex specifically, your solution uses split
    – helado
    Commented Dec 20, 2019 at 23:40
4
^(.*?)(?=\?|$)

You can try this.See demo.

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

1
  • @Anonymous are there more types of inputs?Can you add them too
    – vks
    Commented Dec 19, 2014 at 11:31
2

Simple alternative:

hash = str.substr(0, (str + "?").indexOf("?"));
1
  • OP asked for a regex specifically, your solution uses substr
    – helado
    Commented Dec 20, 2019 at 23:40
1

You can use:

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

This will always return string before first ? whether or not ? is present in input.

RegEx Demo

0

Either I'm missing something or simply:

 ^#\w+

Seems to do the job for both(this and this) scenarios

Not the answer you're looking for? Browse other questions tagged or ask your own question.