Why does string.match(…)[0] throws an exception?

∥☆過路亽.° 提交于 2021-02-05 11:19:26

问题


I'm trying to pull the first occurence of a regex pattern from a string all in one statement to make my code look cleaner. This is what I want to do:

var matchedString = somestring.match(/some regex/g)[0];

I would expect this to be legal but it throws an exception:

Exception: somestring.match(...) is null

It seems like JS is trying to index the array before match is finsihed, as the array does provide atleast one match, so I don't expect it to be null.

I would like some insight in why it happens. Could it be a bug?

My machine is a PC running Arch Linux x86_64. The code is being executed within the scratchpad of firefox 32.0.3.

Thanks for your interest.


回答1:


If somestring.match() finds no match, then it returns null.

And, null[0] throws an exception.

Since you are getting this exact exception, your regex is not being found in the content. Be very careful using the g flag on a match option in this way as it does not always do what you expect when you have submatches specified in the regex. Since it looks like you just want the first match anyway, you should probably remove the g option.


A safer way to code is:

var matches = somestring.match(/some regex/);
if (matches) {
    // do something here with matches[0]
}



回答2:


If you want to do it in one statement (and there's no particularly good reason why that is a good idea, see jfriend000's answer), then:

var firstMatchOrFalse = /pattern/.test(somestring) && somestring.match(/pattern/)[0];

and if you only want the first match, why the g flag?



来源:https://stackoverflow.com/questions/26415011/why-does-string-match-0-throws-an-exception

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