JavaScript RegExp:test和exec

9 javascript regex

我希望获得多行文本中的所有图像的URL(无论它包含什么).

这是我的代码:

var pattern = /(http:\/\/\S+\.(?:jpg|gif|png|jpeg|JPG|GIF|PNG|JPEG))/mg;
var testResult = pattern.test(str));
var result = pattern.exec(str);
Run Code Online (Sandbox Code Playgroud)

如果str等于"http://example.dom.com/-6/x_5eb0916a.jpg",则testResult等于true结果null.为什么?你能帮我解决这个问题吗?

pim*_*vdb 8

那是因为g旗帜.如果您反转这两个调用,您将得到不同的结果,因为全局标志设置pattern.lastIndex并在下次调用.test/ 时从该索引开始匹配.exec.当反转呼叫时,你会得到一个非null结果.exec,并且false.test.

使用.lastIndex和全局标志,在您的情况下它匹配的URL .test,并将在您执行时第一个URL 之后开始查找更多URL .exec.没有更多的网址,所以你会得到null.请注意,lastIndex然后重置为0,因此.exec再次调用将起作用.

无论如何,你似乎正在寻找str.match(pattern),它只是列出所有匹配:

var str = " test http://example.dom.com/-6/x_5eb0916a.jpg"
             + " \nfoo http://example2.com/test.png";

var pattern = /(http:\/\/\S+\.(?:jpg|gif|png|jpeg|JPG|GIF|PNG|JPEG))/gm;

str.match(pattern);
// ["http://example.dom.com/-6/x_5eb0916a.jpg", "http://example2.com/test.png"]
Run Code Online (Sandbox Code Playgroud)