简单的正则表达式:尝试matchURL字符串为空

问题描述

我对正则表达式非常陌生,可以肯定地说我很困惑。

我有一个具有以下URL结构的库存站点: www.example.com/asx/symbol

我正在尝试使用Javascript和regex来匹配'symbol'字符串。

例如,www.example.com/asx/tls将匹配(并返回)'tls'(但前提是'/ asx /'在它之前)。

如果网址更改为www.example.com/asx/cba,则将返回'cba'。

function () {
                    var qs = window.location.search || "";
                    var m = qs.match(/asx\/([a-z0-9]+)/i);
                    console.log(m);
                    return m ? m[1] : "";

console.log返回始终为NULL,我无法弄清原因。我已经花了几个小时了,阅读了太多的教程并尝试了regex101 ...

它说:“ /必须使用反斜杠()来转义未转义的分隔符”

但是当我添加... / i时,它与主题字符串不匹配。

我希望有人可以帮助新手。

谢谢!

解决方法

const url = 'www.example.com/asx/symbol'
const match = url.match(/asx\/[\D]*/g).join('').split('/').slice(1).join('');
console.log(match)

,

您不能使用window.location.search获取路径名(window.location.search:return the querystring part of a URL)。您只需将window.location.pathname替换window.location.search。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...