Reputation: 1461
I have a text, example:
Hello ../aaa.jpg ../bbb.jpg ../sss.gif ../xxx.png End of Text
I want to get all text with extension jpg and png.
Expected result:
1. ../aaa
2. ../bbb
3. ../xxx
I try with .match(/(.*).(jpg|png)/)
, but it seems not working as expected
Upvotes: 3
Views: 73
Reputation: 91518
let regex = /\S+?(?=\.(?:jpg|png))/g
console.log(
'Hello ../aaa.jpg blah ../a-b-c.jpg ../sss.gif ../&%01-x.png End of Text'.match(regex)
)
Where
\S+?
matches 1 or more (not greedy) non space character(?= ... )
is a positive lookahead(?: ... )
is a non capture groupUpvotes: 2
Reputation: 10096
You have to use the g
flag for this to work on multiple occurrences, and you need to match only words (\w
), the dot (\.
) and slash (\/
) before the dot and the extension:
let re = /([\w\.\/]*)\.(?:jpg|png)/g
console.log(
'Hello ../aaa.jpg ../bbb.jpg ../sss.gif ../xxx.png End of Text'.match(re)
)
Upvotes: 3