Skip to main content

How to manipulate a string

These Calculated Field expressions reshape a text value: inserting punctuation at fixed positions, stripping characters, padding to a fixed width, and splitting a delimited value apart. Replace fieldAliasGoesHere with the alias of your Field.

Add hyphens at fixed positions to a string​

Uses substring().

// Input: A string with value "1234567890"
// Output: A new string with value "123-456-7890"

var numericString = $record['fieldAliasGoesHere'];
var formattedString = numericString.substring(0, 3) + "-" + numericString.substring(3, 6) + "-" + numericString.substring(6, 10);

formattedString;

Add parentheses and hyphens at fixed positions to a string​

Uses substring().

// Input: A string with value "1234567890"
// Output: A new string with value "(123) 456-7890"

var numericString = $record['fieldAliasGoesHere'];
var formattedString = "(" + numericString.substring(0, 3) + ") " + numericString.substring(3, 6) + "-" + numericString.substring(6, 10);

formattedString;

Remove all hyphens from a string​

Uses replace(). The g flag replaces every hyphen, not only the first.

// Input: A string with value "123-456-7890"
// Output: A new string with value "1234567890"

var stringWithHyphens = $record['fieldAliasGoesHere'];
var stringWithoutHyphens = stringWithHyphens.replace(/-/g, "");

stringWithoutHyphens;

Remove all non-alphanumeric characters​

Uses replace(). The pattern keeps letters, digits, and spaces and removes everything else. To remove spaces too, delete the space inside the brackets.

// Input: A string with value "123-456-7890"
// Output: A new string with value "1234567890"

var stringWithSpecialCharacters = $record['fieldAliasGoesHere'];
var stringWithoutSpecialCharacters = stringWithSpecialCharacters.replace(/[^a-zA-Z0-9 ]+/g, "");

stringWithoutSpecialCharacters;

Pad a string to the left​

Uses _.padLeft().

// Input: A string with value "12345"
// Output: A new string with value "0012345"

var string = $record['fieldAliasGoesHere'];
var formattedString = _.padLeft(string, 7, "0");

formattedString;
note

The _ library in Informer scripts is lodash 3, so use _.padLeft() and _.padRight(). The lodash 4 names, _.padStart() and _.padEnd(), are not available.

Pad a string to the right​

Uses _.padRight().

// Input: A string with value "12345"
// Output: A new string with value "1234500"

var string = $record['fieldAliasGoesHere'];
var formattedString = _.padRight(string, 7, "0");

formattedString;

Turn a comma-delimited string into an array of substrings​

Uses split(). Each piece of the result is still a string.

// Input: A string with value "1,2,3,4,5"
// Output: An array with value ["1", "2", "3", "4", "5"]

var exampleString = $record['fieldAliasGoesHere'];
var array = exampleString.split(",");

array;

To go the other way, from an array back to a delimited string, see Turn an array into a comma-delimited string.