我正在执行一个简单的Lookbehind断言来获取URL的一段(如下例所示),但是没有得到匹配结果,而是得到了以下错误:
Uncaught SyntaxError: Invalid regular expression: /(?<=\#\!\/)([^\/]+)/: Invalid group下面是我正在运行的脚本:
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 ) );结果应该是write-stuff。
有人能解释一下这个正则表达式组导致这个错误的原因吗?在我看来,这是一个有效的RegEx。
我知道如何获得我需要的细分市场的替代方案,所以这实际上只是帮助我了解这里发生了什么,而不是获得替代解决方案。
感谢您的阅读。
J.
发布于 2011-05-12 13:50:24
我相信JavaScript不支持正向回溯。你将不得不做更多像这样的事情:
<script>
var regex = /\#\!\/([^\/]+)/;
var url = "http://my.domain.com/index.php/#!/write-stuff/something-else";
var match = regex.exec(url);
alert(match[1]);
</script>发布于 2011-05-12 13:51:33
Javascript不支持后视语法,所以(?<=)是导致无效错误的原因。但是,您可以使用各种技术来模仿它:http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
发布于 2020-07-15 15:12:13
此外,在全局(/g)或粘滞标志(/s)未设置的情况下,您可以使用String.prototype.match()而不是RegExp.prototype.exec()。
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"https://stackoverflow.com/questions/5973669
复制相似问题