0

I have this url:

http://example.com/categories/listing/all-categories?src=home

And I was testing online for regex here and ended up to this:

[^/]*(?=\?)

I want the part between asterisk http://example.com/categories/listing/*all-categories*?src=home

In my javascript I wrote this:

var reg = /[^\/]*(?=\?)/i;
var url = document.location.href;
var subcat = reg.exec(url);
alert(subcat);

But nothing alerts, what I doing wrong?

6
  • This regex works with me! Commented Mar 19, 2014 at 10:40
  • I think your problem is with document.location.href. What does alert(url) give? Commented Mar 19, 2014 at 10:42
  • Also, you don't need to escape the / inside the character class, and the case insensitive flag does not do anything here either. This will not fix your problem, just a note. So it can be simplified to: /[^/]*(?=\?)/ Commented Mar 19, 2014 at 10:43
  • 1
    @DaniëlKnippers: The / must always be escaped within a JavaScript regex literal. Otherwise it would be interpreted as a regex delimiter, causing a Syntax Error. The /i is indeed superfluous. Commented Mar 19, 2014 at 10:46
  • @TimPietzcker Not inside a character class. Only ^, `, ]` and - should be escaped. Did you try the regex I posted, no syntax error. More on it here: regular-expressions.info/charclass.html Commented Mar 19, 2014 at 10:49

1 Answer 1

2

this is working for me

var reg = /[^\/]*(?=\?)/i;
var url = "http://example.com/categories/listing/all-categories?src=home";
var subcat = reg.exec(url);
console.log(subcat);

i think your document.location.href is something else, please check it

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.