String Functions and Properties

String functions provide powerful ways to manipulate, search, and transform text data in expressions. These methods are similar to JavaScript string methods and enable text processing without requiring additional Snaps.

String Literals

String literals can be constructed with either single quotes or double quotes, similar to JavaScript strings.

Syntax:

"Bob" or 'Bob'

Escape Sequences:

// Escape double quotes
"\"Bob\""    // Returns: "Bob"

// Escape single quotes
'\'Bob\''    // Returns: 'Bob'

Static Methods

String.fromCharCode()

Returns a string created by using the specified sequence of Unicode values.

This is similar to the JavaScript fromCharCode.

Syntax:

String.fromCharCode(num1[, num2, ...])

Example:

String.fromCharCode(69, 97, 116, 32, 114, 105, 103, 104, 116)
// Returns: "Eat right"

String.fromCharCode(72, 101, 108, 108, 111)
// Returns: "Hello"

Case Transformation Methods

camelCase()

Returns the string in camelCase. This is similar to the Lodash camelCase.

$tag.camelCase()
// Where $tag = "sim_world"
// Returns: "simWorld"

"hello-world".camelCase()
// Returns: "helloWorld"

capitalize()

Returns the first character in upper case and the remaining characters in lower case. This is similar to the Lodash capitalize.

$first.capitalize()
// Where $first = "JANE"
// Returns: "Jane"

"hello world".capitalize()
// Returns: "Hello world"

kebabCase()

Returns the string in kebab-case. This is similar to the Lodash kebabCase.

$action.kebabCase()
// Where $action = "Check_in"
// Returns: "check-in"

"HelloWorld".kebabCase()
// Returns: "hello-world"

snakeCase()

Returns the string in snake_case. This is similar to the Lodash snakeCase.

$category.snakeCase()
// Where $category = "LevelCritical"
// Returns: "level_critical"

"HelloWorld".snakeCase()
// Returns: "hello_world"

toLowerCase()

Returns the value of the string converted to lower case. This is similar to the JavaScript toLowerCase.

$login.toLowerCase()
// Where $login = "[email protected]"
// Returns: "[email protected]"

toUpperCase()

Returns the value of the string converted to uppercase. This is similar to the JavaScript toUpperCase.

$login.toUpperCase()
// Where $login = "[email protected]"
// Returns: "[email protected]"

lowerFirst()

Returns the string with the first character in lower case. This is similar to the Lodash lowerFirst.

$msg.lowerFirst()
// Where $msg = "FOOBAR"
// Returns: "fOOBAR"

upperFirst()

Returns the string with the first character in upper case. This is similar to the Lodash upperFirst.

$msg.upperFirst()
// Where $msg = "foobar"
// Returns: "Foobar"

String Inspection Methods

length

Returns the number of code units in the string. This is similar to the JavaScript length property.

$first.length
// Where $first = "John"
// Returns: 4

"Hello".length
// Returns: 5

charAt()

Returns the character at the specified index. This is similar to the JavaScript charAt.

$first.charAt(0)
// Where $first = "John"
// Returns: "J"

"Hello".charAt(4)
// Returns: "o"

charCodeAt()

Returns the numeric Unicode value of the character at the given index. This is similar to the JavaScript charCodeAt.

$first.charCodeAt(0)
// Where $first = "Dan"
// Returns: 68

"A".charCodeAt(0)
// Returns: 65

Search and Match Methods

contains()

Returns true or false after determining if one string can be found within another. If position is specified, the search will begin there. This is similar to the JavaScript includes.

$msg.contains('Hello')
// Where $msg = "Hello, World"
// Returns: true

$msg.contains('Hello', 8)
// Where $msg = "Hello, World"
// Returns: false (because "Hello" exists before position 8)

startsWith()

Returns true or false after determining if one string starts with the characters of another. This is similar to the JavaScript startsWith.

$string.startsWith("Copyright")
// Where $string = "Copyright 2017"
// Returns: true

$string.startsWith("2017", 10)
// Where $string = "Copyright 2017"
// Returns: true

endsWith()

Returns true or false after determining if one string ends with the characters of another. This is similar to the JavaScript endsWith.

$email.endsWith("@example.com")
// Returns: true

$bootstrapping.endsWith("strapping", 13)
// Returns: true

indexOf()

Returns the index of the first occurrence of the specified value, or -1 if not found. This is similar to the JavaScript indexOf.

$city.indexOf("San")
// Where $city = "San Francisco"
// Returns: 0

$city.indexOf("Jose", 0)
// Where $city = "San Jose"
// Returns: 4

lastIndexOf()

Returns the index of the last occurrence of the specified value, or -1 if not found. This is similar to the JavaScript lastIndexOf.

$email.lastIndexOf("e")
// Where $email = "[email protected]"
// Returns: 10

search()

Returns the index of the first match of a regular expression, or -1 if not found. This is similar to the JavaScript search.

$String.search("score")
// Where $String = "Four score and seven years ago"
// Returns: 5

$text.search(/\d+/)
// Finds first number in text

match()

Returns an array of results when matching a string against a regular expression. This is similar to the JavaScript match.

// Match whole word
$FirstName.match(/\bJohn\b/g)
// Returns: ["John"]

// Match employee ID pattern
$EMPLOYEE_CODE.match($employee_id + "-\\d{5,}")

// Extract all numbers
$text.match(/\d+/g)

String Manipulation Methods

concat()

Combines the text of two or more strings and returns a new string. This is similar to the JavaScript concat.

$first.concat($last)
// Where $first = "John" and $last = "Doe"
// Returns: "JohnDoe"

$first.concat(" ", $last)
// Where $first = "John" and $last = "Doe"
// Returns: "John Doe"

replace()

Returns a new string with some or all matches of a pattern replaced by another. This is similar to the JavaScript replace.

$msg.replace("l", "x")
// Where $msg = "Hello, World"
// Returns: "Hexlo, World" (only first match)

// Case insensitive with /i flag
$msg.replace(/world/i, "my friend")
// Where $msg = "Hello, World"
// Returns: "Hello, my friend"

// Global replace with /g flag
$msg.replace(/l/g, "x")
// Where $msg = "Hello World"
// Returns: "Hexxo Worxd"

// Replace forward slashes
$inputstring.replace(/\//g, "_")
// Where $inputstring = "/org/projectspace/project"
// Returns: "_org_projectspace_project"

// Using callback function to capitalize words
$msg.replace(/\b([a-z])(\w+)\b/g, (_matched, first, rest) => first.toUpperCase() + rest.toLowerCase())
// Where $msg = "hello, world!"
// Returns: "Hello, World!"

replaceAll()

Returns a new string with all matches of a pattern replaced by another.

$msg.replaceAll("l", "1")
// Where $msg = "All letters"
// Returns: "A11 1etters"

repeat()

Returns a new string containing the specified number of copies of the string. This is similar to the JavaScript repeat.

$string.repeat(3)
// Where $string = "Hello"
// Returns: "HelloHelloHello"

"=".repeat(10)
// Returns: "=========="

split()

Returns an array of strings divided at the supplied separator. This is similar to the JavaScript split.

$Location.split('/')
// Where $Location = "/snaplogic/projects/DocTest"
// Returns: ["", "snaplogic", "projects", "DocTest"]

$Location.split('/', 3)
// Where $Location = "/Snaplogic/projects/DocTest"
// Returns: ["", "Snaplogic", "projects"]

// Split at newline
$text.split('\n')

// Split name into parts
$name.split(' ')
// Where $name = "John Paul Jones"
// Returns: ["John", "Paul", "Jones"]

sprintf()

Swaps out parts of the string using placeholders with values. Similar to JavaScript sprintf() with extended functionality from java.util.Formatter.

$msg.sprintf("from", "SnapLogic")
// Where $msg = "hello %s %s"
// Returns: "hello from SnapLogic"

// Positional arguments
$msg.sprintf("Snaplogic", "from")
// Where $msg = "hello %2$s %1$s"
// Returns: "hello from Snaplogic"

Substring Methods

slice()

Returns a new string with text extracted from another string. This is similar to the JavaScript slice.

$String.slice(10)
// Where $String = "Copyright 2017 All rights reserved."
// Returns: "2017 All rights reserved."

$String.slice(10, 14)
// Where $String = "Copyright 2017 All rights reserved."
// Returns: "2017"

$String.slice(10, -2)
// Where $String = "Copyright 2017 All rights reserved."
// Returns: "2017 All rights reserve"

$String.slice(-2)
// Where $String = "Copyright 2017 All rights reserved."
// Returns: "d."

substr()

Returns the characters in a string beginning at the specified location through the specified number of characters. This is similar to the JavaScript substr.

$first.substr(0, 1)
// Where $first = "John"
// Returns: "J"

"SnapLogic".substr(4, 5)
// Returns: "Logic"

substring()

Returns a subset of a string between one index and another, or through the end of the string. This is similar to the JavaScript substring.

"SnapLogic".substring(4)
// Returns: "Logic"

"SnapLogic".substring(0, 4)
// Returns: "Snap"

Whitespace Methods

trim()

Returns the string stripped of whitespace from both ends. This is similar to the JavaScript trim.

$string.trim()
// Where $string = " test "
// Returns: "test"

trimLeft()

Returns the string stripped of whitespace from the left end. This is similar to the JavaScript trimLeft.

$string.trimLeft()
// Where $string = " test"
// Returns: "test"

trimRight()

Returns the string stripped of whitespace from the right end. This is similar to the JavaScript trimRight.

$string.trimRight()
// Where $string = "test "
// Returns: "test"

String Comparison

localeCompare()

Compares this string to another and returns a number representing sort order. This is similar to the JavaScript localeCompare.

  • Negative number - This string comes before the given one
  • Zero - This string is equal to the given one
  • Positive number - This string comes after the given one
"a".localeCompare("b")
// Returns: negative number

"b".localeCompare("a")
// Returns: positive number

"apple".localeCompare("apple")
// Returns: 0

Common Patterns

Check for Non-empty String:

// Use trim() and logical OR for default value
$customer.lastname.trim() || 'default'

Check for Existing Value:

// Use hasOwnProperty for null-safe access
$.hasOwnProperty('customer.lastname') ? $customer.lastname : 'default'

Check for Non-empty String AND Existing Value:

($.hasOwnProperty('customer.lastname') && $customer.lastname.trim()) || 'default'

Create Email from First Initial and Last Name:

$first_name.substr(0, 1).toLowerCase() + $last_name.toLowerCase() + "@example.com"
// Where $first_name = "John" and $last_name = "Doe"
// Returns: "[email protected]"

Extract Filename from Path:

$path.split('/').slice(-1)[0]
// Where $path = "/org/project/file.txt"
// Returns: "file.txt"

Normalize Whitespace:

$text.trim().replace(/\s+/g, ' ')
// Removes leading/trailing whitespace and collapses multiple spaces

Capitalize Each Word:

$text.replace(/\b([a-z])(\w+)\b/g, (_matched, first, rest) => first.toUpperCase() + rest.toLowerCase())
// Where $text = "hello world"
// Returns: "Hello World"

Safe String Concatenation:

// Use concat() or template-style concatenation
$first.concat(" ", $last)
// OR
$first + " " + $last

Best Practices

  • Immutability: String methods return new strings rather than modifying the original.
  • Null Safety: Always check for null or undefined before calling string methods using hasOwnProperty() or optional chaining.
  • Case Sensitivity: Use toLowerCase() or toUpperCase() when comparing strings for case-insensitive matching.
  • Regular Expressions: Use regex flags (/i for case-insensitive, /g for global) to control match behavior in replace() and match().
  • Performance: For multiple replacements, use replaceAll() or replace() with /g flag instead of chaining multiple replace() calls.
  • Whitespace: Always trim() user input to remove leading/trailing whitespace before validation or comparison.
  • Empty Strings: Use .trim() || 'default' pattern to handle both empty strings and whitespace-only strings.
  • Escape Characters: Remember to escape special regex characters when using them in patterns.
  • Unicode: Be aware that length counts UTF-16 code units, not Unicode characters.

Method Comparison

Method Purpose Returns Example
charAt() Get character at index String "abc".charAt(0) → "a"
indexOf() Find first occurrence Number "abc".indexOf("b") → 1
lastIndexOf() Find last occurrence Number "abcb".lastIndexOf("b") → 3
slice() Extract substring String "abc".slice(1) → "bc"
substring() Extract substring String "abc".substring(1) → "bc"
substr() Extract by length String "abc".substr(1, 2) → "bc"
split() Convert to array Array "a,b".split(",") → ["a","b"]
concat() Combine strings String "a".concat("b") → "ab"
replace() Replace pattern String "abc".replace("b","x") → "axc"
trim() Remove whitespace String " a ".trim() → "a"
toLowerCase() Convert to lower String "ABC".toLowerCase() → "abc"
toUpperCase() Convert to upper String "abc".toUpperCase() → "ABC"