Copy link to clipboard
Copied
I have an old Photoshop script from circa 2012 - which I remember working, that uses the trim() function. Strings, not pixels - let's make that clear.
var text = " Hello Spoons! ";
var result = text.trim();
alert(result)
However, something like the code above no longer works. text.trim is not a function.
I can use reg ex to trim the string, but my question is this:
Has Photoshop scripting changed/updated it's version of ECMA Script (ver 3.x???) to no longer include trim?
trim() is an ECMAScript5 (ES5) feature.
Copy link to clipboard
Copied
The Object Model Viewer doesn't show trim() as a supported function.
Copy link to clipboard
Copied
Did it ever though?
Copy link to clipboard
Copied
trim is a method of document, so trying to apply it to some text seems pointless.
Copy link to clipboard
Copied
trim() is an ECMAScript5 (ES5) feature.
Copy link to clipboard
Copied
https://www.w3schools.com/jsref/jsref_trim_string.asp
Properly its string.trim() but its apparently not implemented in ExtendScript.
Copy link to clipboard
Copied
Hi @Ghoul Fool,
As mentioned by other members, this method is not available in ExtendScript. You can use the following link to see the methods/properties available to use in ExtendScript
https://www.indesignjs.de/extendscriptAPI/photoshop-latest/#String.html
As @jazz-y mentioned trim was introduced in ECMA5 and Extendscript uses ECMA3 so that explains this.
Now as a replacement you could write you own version of a simple trim method like the following
function trim(str){
return str.replace(/\s*(\S*)\s*/, "$1")
}
-Manan
Copy link to clipboard
Copied
Thanks for the confirmation - I'd go with
^\s+|\s+$
as I don't want to remove ALL spaces - just white space at the start and end.
Incidentally, as c.pfaffenbichler mentioned, isn't using "trim" as a function going to cause problems even though they are evoked differently: canvas.trim() versus trim(str)?
Copy link to clipboard
Copied
No that shouldn't be a problem at all. We have same named functions in different objects all the time and they seem to work well.
-Manan
Copy link to clipboard
Copied
Use this polyfill. Put it somewhere near top of script before calling trim on a string.
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
};
}
Copy link to clipboard
Copied
I have an include file with my script pack where I define a couple of utility functions. It can be a prototype or just an object, either works fine.