9

I'm doing a simple Lookbehind Assertion to get a segment of the URL (example below) but instead of getting the match I get the following error:

Uncaught SyntaxError: Invalid regular expression: /(?<=\#\!\/)([^\/]+)/: Invalid group

Here is the script I'm running:

var url = window.location.toString();

url == http://my.domain.com/index.php/#!/write-stuff/something-else

// lookbehind to only match the segment after the hash-bang.

var regex = /(?<=\#\!\/)([^\/]+)/i; 
console.log('test this url: ', url, 'we found this match: ', url.match( regex ) );

the result should be write-stuff.

Can anyone shed some light on why this regex group is causing this error? Looks like a valid RegEx to me.

I know of alternatives on how to get the segment I need, so this is really just about helping me understand what's going on here rather than getting an alternative solution.

Thanks for reading.

J.

Jannis
  • 17,025
  • 18
  • 62
  • 75
  • Can you give some example input string and what part of it must be matched by regex? – Shekhar May 12 '11 at 05:36
  • I've moved it from within the code block to the main example. Updated above. Please let me know if you'd like more detail and I will happily post it. – Jannis May 12 '11 at 05:45

3 Answers3

11

I believe JavaScript does not support positive lookbehind. You will have to do something more like this:

<script>
var regex = /\#\!\/([^\/]+)/;
var url = "http://my.domain.com/index.php/#!/write-stuff/something-else";
var match = regex.exec(url);
alert(match[1]);
</script>
Trott
  • 66,479
  • 23
  • 173
  • 212
7

Javascript doesn't support look-behind syntax, so the (?<=) is what's causing the invalidity error. However, you can mimick it with various techniques: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

mVChr
  • 49,587
  • 11
  • 107
  • 104
0

Also you could use String.prototype.match() instead of RegExp.prototype.exec() in the case of global(/g) or sticky flags(/s) are not set.

var regex = /\#\!\/([^\/]+)/;
var url = "http://my.domain.com/index.php/#!/write-stuff/something-else";
var match = url.match(regex); // ["#!/write-stuff", "write-stuff", index: 31, etc.,]
console.log(match[1]); // "write-stuff"
SridharKritha
  • 8,481
  • 2
  • 52
  • 43