Skip to Content

String Manipulation Utilities

Reusable functions for string operations and text processing.

#string #utilities #formatting #validation #email #phone #text-processing

Script Code

JavaScript
1var StringUtils = Class.create();
2StringUtils.prototype = {
3
4  /**
5   * Truncate string to specified length and add ellipsis
6   *
7   * @param {string} str - String to truncate
8   * @param {number} maxLength - Maximum length
9   * @param {string} suffix - Suffix to add (default: '...')
10   * @returns {string} Truncated string
11   */
12  truncate: function(str, maxLength, suffix) {
13    if (!str || str.length <= maxLength) {
14      return str;
15    }
16
17    suffix = suffix || '...';
18    var trimmedLength = maxLength - suffix.length;
19
20    return str.substring(0, trimmedLength) + suffix;
21  },
22
23  /**
24   * Convert string to title case (capitalize first letter of each word)
25   *
26   * @param {string} str - String to convert
27   * @returns {string} Title cased string
28   */
29  toTitleCase: function(str) {
30    if (!str) {
31      return '';
32    }
33
34    return str.toLowerCase().replace(/\b\w/g, function(char) {
35      return char.toUpperCase();
36    });
37  },
38
39  /**
40   * Convert string to camelCase
41   *
42   * @param {string} str - String to convert
43   * @returns {string} camelCase string
44   */
45  toCamelCase: function(str) {
46    if (!str) {
47      return '';
48    }
49
50    return str
51      .toLowerCase()
52      .replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr) {
53        return chr.toUpperCase();
54      });
55  },
56
57  /**
58   * Convert string to snake_case
59   *
60   * @param {string} str - String to convert
61   * @returns {string} snake_case string
62   */
63  toSnakeCase: function(str) {
64    if (!str) {
65      return '';
66    }
67
68    return str
69      .replace(/\W+/g, ' ')
70      .split(/ |\B(?=[A-Z])/)
71      .map(function(word) { return word.toLowerCase(); })
72      .join('_');
73  },
74
75  /**
76   * Remove HTML tags from string
77   *
78   * @param {string} html - HTML string
79   * @returns {string} Plain text
80   */
81  stripHtml: function(html) {
82    if (!html) {
83      return '';
84    }
85
86    return html.replace(/<[^>]*>/g, '');
87  },
88
89  /**
90   * Extract email addresses from text
91   *
92   * @param {string} text - Text containing email addresses
93   * @returns {Array} Array of email addresses found
94   */
95  extractEmails: function(text) {
96    if (!text) {
97      return [];
98    }
99
100    var emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
101    var matches = text.match(emailRegex);
102
103    return matches || [];
104  },
105
106  /**
107   * Mask sensitive data (e.g., SSN, credit card)
108   *
109   * @param {string} str - String to mask
110   * @param {number} visibleChars - Number of characters to leave visible at end
111   * @param {string} maskChar - Character to use for masking (default: '*')
112   * @returns {string} Masked string
113   */
114  maskString: function(str, visibleChars, maskChar) {
115    if (!str) {
116      return '';
117    }
118
119    visibleChars = visibleChars || 4;
120    maskChar = maskChar || '*';
121
122    if (str.length <= visibleChars) {
123      return str;
124    }
125
126    var masked = '';
127    for (var i = 0; i < str.length - visibleChars; i++) {
128      masked += maskChar;
129    }
130
131    return masked + str.substring(str.length - visibleChars);
132  },
133
134  /**
135   * Generate a slug from text (URL-friendly string)
136   *
137   * @param {string} text - Text to convert
138   * @returns {string} URL-friendly slug
139   */
140  slugify: function(text) {
141    if (!text) {
142      return '';
143    }
144
145    return text
146      .toLowerCase()
147      .trim()
148      .replace(/[^\w\s-]/g, '')  // Remove special chars
149      .replace(/[\s_-]+/g, '-')  // Replace spaces with -
150      .replace(/^-+|-+$/g, '');  // Trim - from ends
151  },
152
153  /**
154   * Count words in text
155   *
156   * @param {string} text - Text to count
157   * @returns {number} Word count
158   */
159  wordCount: function(text) {
160    if (!text) {
161      return 0;
162    }
163
164    return text.trim().split(/\s+/).length;
165  },
166
167  /**
168   * Check if string is valid email
169   *
170   * @param {string} email - Email to validate
171   * @returns {boolean} True if valid email format
172   */
173  isValidEmail: function(email) {
174    if (!email) {
175      return false;
176    }
177
178    var emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
179    return emailRegex.test(email);
180  },
181
182  /**
183   * Check if string is valid phone number (US format)
184   *
185   * @param {string} phone - Phone number to validate
186   * @returns {boolean} True if valid phone format
187   */
188  isValidPhone: function(phone) {
189    if (!phone) {
190      return false;
191    }
192
193    // Remove all non-digits
194    var digits = phone.replace(/\D/g, '');
195
196    // Check for valid length (10 or 11 digits with country code)
197    return digits.length === 10 || digits.length === 11;
198  },
199
200  /**
201   * Format phone number to standard format
202   *
203   * @param {string} phone - Phone number to format
204   * @param {string} format - Format type: 'us' (default), 'international'
205   * @returns {string} Formatted phone number
206   */
207  formatPhone: function(phone, format) {
208    if (!phone) {
209      return '';
210    }
211
212    format = format || 'us';
213    var digits = phone.replace(/\D/g, '');
214
215    if (format === 'us' && digits.length === 10) {
216      return '(' + digits.substring(0, 3) + ') ' +
217             digits.substring(3, 6) + '-' +
218             digits.substring(6);
219    } else if (format === 'international' && digits.length === 11) {
220      return '+' + digits.substring(0, 1) + ' (' +
221             digits.substring(1, 4) + ') ' +
222             digits.substring(4, 7) + '-' +
223             digits.substring(7);
224    }
225
226    return phone;  // Return original if can't format
227  },
228
229  /**
230   * Generate random string
231   *
232   * @param {number} length - Length of string to generate
233   * @param {string} charset - Character set: 'alphanumeric' (default), 'alpha', 'numeric'
234   * @returns {string} Random string
235   */
236  generateRandom: function(length, charset) {
237    length = length || 10;
238    charset = charset || 'alphanumeric';
239
240    var chars = '';
241    if (charset === 'alpha') {
242      chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
243    } else if (charset === 'numeric') {
244      chars = '0123456789';
245    } else {
246      chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
247    }
248
249    var result = '';
250    for (var i = 0; i < length; i++) {
251      result += chars.charAt(Math.floor(Math.random() * chars.length));
252    }
253
254    return result;
255  },
256
257  type: 'StringUtils'
258};

How to Use

1. Create a new Script Include 2. Set Name to "StringUtils" 3. Leave "Client callable" unchecked 4. Copy the code above 5. Call from Business Rules or other Script Includes

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts