最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - JavaScript RegExp: test and exec - Stack Overflow

programmeradmin5浏览0评论

I want to get URLs of all images in multiline text (no matter what it contains).

This is my code:

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

If str equals ".jpg", testResult equals true but result is null. Why? Would you help me to solve this problem?

I want to get URLs of all images in multiline text (no matter what it contains).

This is my code:

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

If str equals "http://example.dom./-6/x_5eb0916a.jpg", testResult equals true but result is null. Why? Would you help me to solve this problem?

Share Improve this question asked Jan 7, 2012 at 11:39 user1025125user1025125 2
  • You have one ) too much at the end of line 2. Also what is str? It's undefined in your code. – js-coder Commented Jan 7, 2012 at 11:52
  • 1 It could be helpful to add a \/ between your domain and file extension patterns, to prevent subdomains from being parsed otherwise http://some.png.example./home.html will give you http://some.png (I concede it's just a matter of principle ;) ). – Matteo B. Commented Jan 7, 2012 at 12:22
Add a ment  | 

4 Answers 4

Reset to default 8

That's because of the g flag. If you invert the two calls, you'll get different results because the global flag sets pattern.lastIndex and starts matching from that index the next time you call .test/.exec. When inverting the calls, you'd get a non-null result for .exec, and false for .test.

With .lastIndex and the global flag, in your case it matches the URL for .test, and will start looking for more URLs after the first URL when you execute .exec. There are no more URLs, so you'll get null. Note that lastIndex is then reset to 0, so calling .exec again would work.

Anyhow, you seem to be looking for str.match(pattern) instead, which simply lists all matches:

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

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

str.match(pattern);
// ["http://example.dom./-6/x_5eb0916a.jpg", "http://example2./test.png"]

Solution to this issue is to simply set lastIndex of regex to zero.

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

Did you try this,

"http://example.dom./-6/x_5eb0916a.jpg".match(pattern)

also try returning a function that creates the regex instead of resetting the lastIndex each time.

function getRegex(){
  return /(http:\/\/\S+\.(?:jpg|gif|png|jpeg|JPG|GIF|PNG|JPEG))/mg;
}

const testResult = getRegex().test(str);
发布评论

评论列表(0)

  1. 暂无评论