-1

I have a string with a list of filenames such as

var string = '1.jpg,2.jpg,3.png,4.jpg,5.webp'

Is there a way to remove everything that doesn't end in .jpg so the output would look like this:

var newstring = '1.jpg,2.jpg,4.jpg'

Tam2
  • 323
  • 1
  • 5
  • 16
  • With regex: `var newstring = '1.jpg,2.jpg,3.png,4.jpg,5.webp,6.jpgg,7.jjpg,8.jpg'.replace(/,?[^,]+\.(?!jpg(,|$)).+?(?=,|$)/gmi, '');` – MonkeyZeus Nov 21 '19 at 18:31

5 Answers5

7

You may write something like this

 string
        .split(",")
        .filter(value => value.endsWith(".jpg"))
        .join(",")
0

Did you experiment with possible regular expressions you could use? You might be able to find the answer yourself thanks to this page from the Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Yves Gurcan
  • 1,096
  • 1
  • 10
  • 25
0

If your string is always a comma separated list, then split the string on commas, which will give you an array of items. Then splice the array and remove items that contain the .jpg pattern.

bwigs
  • 96
  • 4
0
var string = '1.jpg,2.jpg,3.png,4.jpg,5.webp';
string.split(',').filter((name)=> name.includes('.jpg')).join(',');
//"1.jpg,2.jpg,4.jpg"
Dipak Telangre
  • 1,792
  • 4
  • 19
  • 46
  • Note: includes and ends with is not the same. This will fail on (unlikely?) filenames such as 2.convertedfrom.jpg.to.png – visibleman Nov 21 '19 at 23:21
0

var string = '1.jpg,2.jpg,3.png,4.jpg,5.webp';

var stringArray=string.split(',');
newArray=[];

stringArray.forEach(element => {
  if(element.indexOf('.jpg')>-1){ newArray.push(element)}
});

console.log("jpg Array  :"+newArray)// output : jpg Array  :1.jpg,2.jpg,4.jpg
Jadli
  • 858
  • 1
  • 9
  • 17