Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/RegExp: Lookbehind Assertion is causing a "Invalid group" error

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.

like image 320
Jannis Avatar asked May 12 '11 05:05

Jannis


People also ask

What are lookahead and lookbehind in regex?

In the example below the currency sign (€|kr) is captured, along with the amount: Lookahead and lookbehind (commonly referred to as “lookaround”) are useful when we’d like to match something depending on the context before/after it. For simple regexps we can do the similar thing manually.

What are assertions in JavaScript?

Assertions include boundaries, which indicate the beginnings and endings of lines and words, and other patterns indicating in some way that a match is possible (including look-ahead, look-behind, and conditional expressions). JavaScript Demo: RegExp Assertions.

What does the lookahead assertion mean?

Lookahead assertion: Matches "x" only if "x" is followed by "y". For example, / Jack (?=Sprat)/ matches "Jack" only if it is followed by "Sprat". /Jack (?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost".


1 Answers

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>
like image 140
Trott Avatar answered Sep 30 '22 19:09

Trott