Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18909

JavaScript Regular Expression Help: Match 0 or 1 times but do not capture

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

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382132

You can use

var hash = yourString.match(/#([^/]+)/)[1];

Upvotes: 2

Paul
Paul

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

Related Questions