Mr.Cocococo
Mr.Cocococo

Reputation: 1461

Regex javascript to capture multiple occurrences

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

Answers (2)

Toto
Toto

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 group

Upvotes: 2

Luca Kiebel
Luca Kiebel

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

Related Questions