Javascript / RegExp: Lookbehind Confidence Raises Invalid Group Error

I am doing a simple Lookbehind statement to get the URL segment (example below), but instead of getting a match, I get the following error:

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

Here is the script I am 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 someone shed some light on why this group of regular expressions is causing this error? Looks like a valid RegEx for me.

I know alternatives on how to get the segment that I need, so it really helps me understand what is happening here, rather than getting an alternative solution.

Thank you for reading.

J.

+6
source share
2 answers

I believe JavaScript does not support positive lookbehind. You will need to do something more similar:

 <script> var regex = /\#\!\/([^\/]+)/; var url = "http://my.domain.com/index.php/#!/write-stuff/something-else"; var match = regex.exec(url); alert(match[1]); </script> 
+9
source

Javascript does not support look-behind syntax, therefore (?<=) Causes an invalidation error. However, you can imitate it in various ways: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript

+7
source

Source: https://habr.com/ru/post/887892/


All Articles