Reputation: 18909
I need to return just the portion between a # and the first "/" from a URL. Sometimes the URL may not have a proceeding "/". I am struggling to deal with that scenario in a RegEx:
var url1 = '#some';
var url2 = '#some/parameter';
var hash = /#(.*)\//.exec(url1);
alert(hash[1]); // only want 'some'
var hash = /#(.*)\//.exec(url2);
alert(hash[1]); / only want 'some'
Upvotes: 1
Views: 72
Reputation: 382132
You can use
var hash = yourString.match(/#([^/]+)/)[1];
Upvotes: 2
Reputation: 141839
Use [^/]
to match any character that is not a /
:
var hash = /^#([^/]+)/.exec(url2)[1];
In general if you want to group a sub-expression for a quantifier, but don't want to capture it, you can prefix the sub-expression with ?:
, like so: (?:.*)
.
With the above regex, however, you do want to capture the ([^\]*)
.
Upvotes: 2