Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Regex正在使用Regex tester,但不为我工作_Javascript_Regex - Fatal编程技术网

Javascript Regex正在使用Regex tester,但不为我工作

Javascript Regex正在使用Regex tester,但不为我工作,javascript,regex,Javascript,Regex,我有这个网址: http://example.com/categories/listing/all-categories?src=home 我在网上测试regex,结果是: [^/]*(?=\?) 我想要星号http://example.com/categories/listing/*所有类别*?src=home 在我的javascript中,我写道: var reg = /[^\/]*(?=\?)/i; var url = document.location.href; var subca

我有这个网址:

http://example.com/categories/listing/all-categories?src=home
我在网上测试regex,结果是:

[^/]*(?=\?)
我想要星号
http://example.com/categories/listing/*所有类别*?src=home

在我的javascript中,我写道:

var reg = /[^\/]*(?=\?)/i;
var url = document.location.href;
var subcat = reg.exec(url);
alert(subcat);

但是没有什么提醒,我做错了什么?

这对我很有用

var reg = /[^\/]*(?=\?)/i;
var url = "http://example.com/categories/listing/all-categories?src=home";
var subcat = reg.exec(url);
console.log(subcat);

我想你的
文档.location.href
是另外一回事,请检查它

这个正则表达式对我有用!我认为您的问题在于
document.location.href
alert(url)
给出了什么?另外,您不需要在character类中转义
/
,不区分大小写的标志在这里也不起任何作用。这不会解决你的问题,只是一个提示。因此可以简化为:
/[^/]*(?=\?)/
@DaniëlKnippers:
/
必须始终在JavaScript正则表达式文本中转义。否则,它将被解释为正则表达式分隔符,从而导致语法错误。
/i
确实是多余的。@TimPietzcker不在字符类中。只应转义
^
`、
]`和
-
。你试过我发布的正则表达式了吗,没有语法错误。更多信息请点击此处: