How do I use trim() functions in SSJS? Using Data Extensions. Can you please provide some examples?
I have a Data Extension, where "Message" is an Attribute. In this Attribute how do I use the trim() function for removing unwanted spaces?
How do I use trim() functions in SSJS? Using Data Extensions. Can you please provide some examples?
I have a Data Extension, where "Message" is an Attribute. In this Attribute how do I use the trim() function for removing unwanted spaces?
UPDATE
So I have found out trim() is ECMA 5 and is not available as a native function in SFMC SSJS as that is based on ECMA 3 standards. To be able to utilize, you can use this function to 'backfill' this capability in.
//Polyfill for trim
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
which is utilized like so:
var str = ' TrimMe ';
var trimmed = str.trim();
Original Answer
Trim is a built in Javascript function. The syntax is slightly different than AMPscript, but still simple.
You just use something like below:
var str = ' TrimMe ';
var trimmed = str.trim();
Which would output: TrimMe
to remove all spaces in a string, you would need to do the following with a replace:
var str = ' Trim Me ';
var noSpace = str.replace(/ /g,'');
This would output: TrimMe
The / /g
is doing a global replace on all
characters. If you do with just ' '
it will only replace the first instance of the space.
As far as I know, there is no built in function in SSJS that removes white spaces from a string.
However, you can use AMPScript's function Trim().
In your case, it should be something like:
SET @message = AttributeValue("Message")
SET @trimmedMessage= trim(@message )
I assume you want to remove the spaces and keep the data in the data extension. When dealing with data extensions, I would suggest you to use SQL instead of SSJS. Extending following code, you will be able to create a Query Activity which reads and updates same data extension, keeping the Message clean from whitespaces, left and right. You need to combine both LTRIM and RTRIM as there is no dedicated TRIM function in the SQL version used in SFMC:
SELECT fieldA, fieldB, RTRIM(LTRIM(Message)) AS Message from DataExtension;
Operations on data within data extensions very rarely require SSJS, and also perform best when used in SQL.