Search code examples
javascriptarraysjsxphotoshop-script

Want to remove various strings from filename before save


I have a JSX script I've written for Photoshop and at the end of this script, before saving, I want to check the filename for various strings and remove them if they exist. What I've written so far only removes the first element in the array it encounters - in the case below it hits the regex and then moves on to save.

An example of a filename encountered is: "PRNT-AB-Navy Blush Oil pallet painting-18x24--REV 27x21.jpg"

What I want the resulting name to be is: "AB-Navy Blush Oil pallet painting"

So I need a little help understanding how can I remove all elements of the array that exist in any given filename?

    var array = ["PRNT-", "--REV ", "-REV ", ".jpg", ".tif", ".psd", new RegExp(/\d+[x]\d+/g)];
    var docName = activeDoc.name
        for (var i = array.length; i >= 0; i--) {
            var newName = docName.replace(array[i], '');
        }

Thanks!


Solution

  • Welcome to Stack Overflow.

    I haven't worked out your file name convention but this will replace the string with what you want without having to loop over each element.

    var s = "PRNT-AB-Navy Blush Oil pallet painting-18x24--REV 27x21.jpg";
    
    alert(replace_filename(s));
    
    function replace_filename(str)
    {
      var rexp = new RegExp(/PRNT-|-\d*x\d*|--REV\s+\d*x\d*|.jpg|.tif.psd/gim);
       return str.replace(rexp, "");
    }
    
    // AB-Navy Blush Oil pallet painting