0

I have a string like this

/// cache ml/3/11204_gb.png/// cache ml/3/16917_ar.png/// cache ml/3/52871_au.jpg

I want to match it with regex and if matched then make the string empty
So I want to check if the string start with a '/' and ends with '.png|.jpg' then remove/empty the entire string

3
  • 2
    Hi, what have you tried so far ? Commented Aug 17, 2019 at 7:22
  • So far I have tried this regex scriptValue = "/// cache ml/3/11204_gb.png/// cache ml/3/16917_ar.png/// cache ml/3/52871_au.jpg"; var output = scriptValue.replace(/^\/\/\/\s[a-z]+^(png|jpg)$/, ''); Commented Aug 17, 2019 at 7:38
  • the question is not clear, what parts of the string do you want to match? Commented Aug 17, 2019 at 8:06

2 Answers 2

1

Here'e the regex you want:

/(\/\/\/ cache ml\/\d\/\d{5}_..\.(png|jpg))+/i
  • / is a special character so we have to escape it like this \/
  • cache ml\/3\/\ this part will match "cache ml\3\" exactly assuming its a stable
  • \d{5} will match any 5 digits
  • .. matches any 2 characters
  • . is a special character so we have to escape it like this \.
  • (png|jpg) will match png or jpg
  • we group the whole thing in a group () and use + this mean one or more so the regex will match any number of repetitions above one, not just 3 as your example
  • we use i at the end to make the regex case insensitive.

Now that we have the regex, we use it like this

var myString = "/// cache ml/\d/11204_gb.png/// cache ml/3/16917_ar.png/// cache ml/3/52871_au.jpg"
var myRegex = /(\/\/\/ cache ml\/3\/\d{5}_..\.(png|jpg))+/i
var newString = myString.replace(myRegex, "")


to make the matching more loss when it comes to filenames you can replace d{5}_.. with .* so the regex becomes:

/(\/\/\/ cache ml\/\d\/.*\.(png|jpg))+/i

this will natch any file name with png or jpg extension.

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

3 Comments

your code really works but I have one exception that is 52871_au this name is dynamic; this could be any file name. Can you please change the code accordingly and help me out?
updated the answer, using .* in place of filename should do the trick. good luck :)
don't forget to accept answer and vote up if it helped.
0

Thanks all finally I fix the regex and here it is

var text = scriptValue.replace(/(\/\/\/ cache ml\/\d\/[a-zA-Z0-9_]*\.(png|jpg|jpeg|gif))+/i, '');

1 Comment

[a-zA-Z0-9_]* this can be replaced with .* so it will match any digit or character in whatever language, not just Latin letters. and since we use the i flag you dont need to use a-zA-Z

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.