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

纵饮孤独 提交于 2019-12-17 18:58:12

问题


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.


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/5973669/javascript-regexp-lookbehind-assertion-is-causing-a-invalid-group-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!