The split() function in ServiceNow is a JavaScript String method that divides a string into an array of substrings based on a specified separator. You use it in server-side scripts (Business Rules, Script Includes, ACLs) and client-side scripts (Client Scripts, UI Policies) exactly as you would in standard JavaScript, with the syntax string.split(separator, limit).
Background: Where Split Fits in ServiceNow Scripting
ServiceNow runs on a JavaScript engine (Mozilla Rhino on the server, and the browser’s engine on the client), so all native JavaScript String methods are available. split() is one of the most commonly used because ServiceNow stores many values as delimited strings—comma-separated lists of sys_ids, pipe-delimited field values, or newline-separated records in a multi-line text field.
Unlike some platforms that provide a dedicated gs.split() function, ServiceNow relies on the standard String.prototype.split(). You will often see it paired with join() (the reverse operation) and with the Array methods like forEach() or indexOf() to process the resulting pieces.
How the Split Function Works
The split() method takes two optional parameters:
- separator: The character or regular expression that determines where to break the string. If omitted, the entire string is returned as a single-element array.
- limit: An integer that caps the number of splits. The resulting array will have at most
limitelements, and the last element contains the remainder of the string.
Example in a Business Rule:
var list = 'sys_id1,sys_id2,sys_id3';
var arr = list.split(',');
gs.info('First item: ' + arr[0]); // prints 'First item: sys_id1'
If you use a regular expression as the separator, you can split on multiple characters at once:
var data = 'a;b,c|d';
var parts = data.split(/[;,\|]/); // parts = ['a','b','c','d']
Note that the separator is not included in the resulting array. If the string starts or ends with the separator, you will get empty string elements at the edges.
Common Use Cases in ServiceNow
- Parsing multi-select fields: Multi-select fields (like Category or Assignment Group) store values as a comma-separated list. You can split and iterate to check if a particular value is present.
- Processing CSV or log data: When importing data or reading a sys_script_include that returns a delimited string, split() helps break it into rows or columns.
- Handling URL parameters: In a Client Script, you might split a URL to extract query string values.
- Working with newline-separated text: Splitting on
\nlets you process each line of a multi-line text field.
Example in a Client Script (onChange of a field):
var selected = g_form.getValue('category');
var cats = selected.split(',');
if (cats.indexOf('hardware') != -1) {
g_form.setValue('priority', 2);
}
Choosing the Right Separator and Limit
Selecting a separator is straightforward but has pitfalls. Common separators are commas (,), pipes (|), semicolons (;), and tabs (\t). When the data itself may contain the separator (e.g., a name like “Smith, John” in a comma-separated list), you need a more robust approach—consider using a less common separator like a pipe or a regex that matches the delimiter only when not inside quotes.
The limit parameter is useful when you only need the first few pieces. For example, splitting a date string ‘2025-03-14’ with split('-', 2) gives ['2025','03'], skipping the day. However, be aware that the last element will contain the rest of the string, so if you need the day later, you must split without a limit or re-split the remainder.
Common Problems and How to Avoid Them
- Empty strings: Splitting ‘a,,b’ with ‘,’ gives [‘a’,”,’b’]. If you want to ignore empty values, use a filter:
arr.filter(function(s){return s !== '';}). - Whitespace: Splitting ‘a, b’ on ‘,’ yields [‘a’,’ b’] with a leading space. Use
trim()on each element:arr.map(function(s){return s.trim();}). - Special characters in separator: If you use a regex separator, escape special characters like
.or*with a backslash. For a literal pipe, use'\|'or/\|/. - Null or undefined strings: Calling
split()on a null value throws an error. Always check:if (str) { ... }or useString(str).split(...). - Performance: For very large strings, splitting into a huge array can be memory-intensive. If you only need to check for a substring, use
indexOf()instead.
Split vs. Other String Methods
ServiceNow developers often confuse split() with substring(), slice(), or indexOf(). Here’s a quick comparison:
split()returns an array of substrings based on a delimiter.substring(start, end)returns a single substring between two indices.slice(start, end)is similar tosubstring()but can accept negative indices.indexOf(searchValue)returns the position of the first occurrence, not the substring itself.
For example, to get the domain from an email ‘user@example.com’, you could use email.split('@')[1] or email.substring(email.indexOf('@') + 1). Both work, but split is often more readable when you need multiple parts.
Frequently Asked Questions
Can I use split() in a GlideRecord query?
No, split() is a JavaScript method and cannot be used inside a GlideRecord query condition. To filter on a list, use the IN operator with a comma-separated string directly, e.g., gr.addQuery('sys_id', 'IN', 'id1,id2,id3').
Does split() work in both client and server scripts?
Yes, it is standard JavaScript and works in both environments. However, be mindful of the data types: on the client, form values are strings, so splitting is safe. On the server, if you have a GlideElement, you may need to call getValue() first to get the string.
How do I split a string by newline in ServiceNow?
Use str.split('\n') for a literal newline character. In a multi-line text field, the values are separated by \n (Unix) or \r\n (Windows). To handle both, use str.split(/\r?\n/).
What is the difference between split() and match()?split() divides a string into an array based on a separator. match() extracts substrings that match a regular expression and returns them as an array. For example, 'a1b2c3'.match(/\d/g) returns [‘1′,’2′,’3’], while 'a1b2c3'.split(/\d/) returns [‘a’,’b’,’c’,”].
Can I split a string into a GlideRecord array?
You can split a string into an array of sys_ids, then loop through it and query each record individually. There is no built-in function to directly convert a delimited string into an array of GlideRecord objects.
Alternatives to Split
If you find yourself splitting strings frequently for complex parsing, consider these alternatives:
- GlideStringUtil: Some utility methods like
GlideStringUtil.split()exist, but they are essentially wrappers for the native method. - JSON.parse(): If your data is in JSON format, parse it directly instead of splitting.
- GlideRecord with IN condition: For sys_id lists, use the IN condition to query all records at once, avoiding manual splitting and looping.
- Script Include for reusable parsing: Create a Script Include that encapsulates your splitting logic, especially if you need to handle edge cases like quoted commas or trimming.
For example, a reusable function to split a comma-separated list and trim whitespace:
var ListUtil = Class.create();
ListUtil.prototype = {
initialize: function() {},
splitAndTrim: function(str) {
if (!str) return [];
var arr = str.split(',');
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].trim();
}
return arr;
},
type: 'ListUtil'
};
Then call new ListUtil().splitAndTrim('a, b, c') to get ['a','b','c'].
Related
- Split CSV File with Bash: 5 Real Methods
- Number 5 Battery Equivalent: What It Is and How to Replace It
- PL/SQL Queries for Interview: 20+ Real Questions
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Add Leading Zeros in Excel: Formatting and FormulasTo show a zero before a number in Excel, select the cells and apply a custom number format…
- XLOOKUP with Multiple Matches: How to Return All ResultsTo return all matches with XLOOKUP instead of just the first one, you must combine it with the…
- Excel Return Index of Match? Use MATCH or XMATCHTo return the index (position) of a match in Excel, use the MATCH function for most cases, or…
- PMT Formula by Hand: Calculate Loan Payments ManuallyThe PMT formula by hand is PMT = P * r / (1 - (1 + r)^-n), where…
- Calculate Age in Excel from DOB with a Simple FormulaIf the date of birth (DOB) is in A2, enter =DATEDIF(A2,TODAY(),"Y") in another cell to return age in…
- JavaScript Functions: How They Work and When to Use ThemJavaScript functions are reusable blocks of code that perform a task, and W3Schools teaches their syntax, calling conventions,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.