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 isstr
? 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 otherwisehttp://some.png.example./home.html
will give youhttp://some.png
(I concede it's just a matter of principle ;) ). – Matteo B. Commented Jan 7, 2012 at 12:22
4 Answers
Reset to default 8That'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);