3

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

2 Answers 2

3

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)
)

Sign up to request clarification or add additional context in comments.

1 Comment

They don't want the extensions.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.