Skip to main content
Inspiring
August 2, 2022
Answered

trim() is not a function

  • August 2, 2022
  • 5 replies
  • 4143 views

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?

 

 

 

This topic has been closed for replies.
Correct answer jazz-y

trim() is an ECMAScript5 (ES5) feature.

5 replies

willcampbell7
Legend
August 4, 2022

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, "");
    };
}

 

William Campbell
Legend
August 4, 2022

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.

Community Expert
August 3, 2022

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

-Manan
Inspiring
August 3, 2022

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

 

Community Expert
August 3, 2022

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

-Manan
jazz-yCorrect answer
Legend
August 2, 2022

trim() is an ECMAScript5 (ES5) feature.

Legend
August 2, 2022

https://www.w3schools.com/jsref/jsref_trim_string.asp

Properly its string.trim() but its apparently not implemented in ExtendScript.

c.pfaffenbichler
Community Expert
Community Expert
August 2, 2022

trim is a method of document, so trying to apply it to some text seems pointless. 

Legend
August 2, 2022

The Object Model Viewer doesn't show trim() as a supported function.

Inspiring
August 2, 2022

Did it ever though?