Skip to Content

String Manipulation Utility

Reusable functions for common string operations, formatting, and transformations.

#string #utilities #formatting #validation #text-processing #manipulation

Script Code

JavaScript
1var StringUtils = Class.create();
2StringUtils.prototype = {
3
4  /**
5   * Convert string to title case
6   * @param {string} str
7   * @returns {string}
8   */
9  toTitleCase: function(str) {
10    if (!str) return '';
11
12    return str.toLowerCase().replace(/\b\w/g, function(char) {
13      return char.toUpperCase();
14    });
15  },
16
17  /**
18   * Convert string to camel case
19   * @param {string} str
20   * @returns {string}
21   */
22  toCamelCase: function(str) {
23    if (!str) return '';
24
25    return str.toLowerCase()
26      .replace(/[^a-zA-Z0-9]+(.)/g, function(match, char) {
27        return char.toUpperCase();
28      });
29  },
30
31  /**
32   * Convert string to snake case
33   * @param {string} str
34   * @returns {string}
35   */
36  toSnakeCase: function(str) {
37    if (!str) return '';
38
39    return str
40      .replace(/([A-Z])/g, '_$1')
41      .replace(/[^a-zA-Z0-9]+/g, '_')
42      .toLowerCase()
43      .replace(/^_+|_+$/g, '');
44  },
45
46  /**
47   * Truncate string to specified length with ellipsis
48   * @param {string} str
49   * @param {number} maxLength
50   * @param {string} suffix - Default: '...'
51   * @returns {string}
52   */
53  truncate: function(str, maxLength, suffix) {
54    if (!str) return '';
55    suffix = suffix || '...';
56
57    if (str.length <= maxLength) {
58      return str;
59    }
60
61    return str.substring(0, maxLength - suffix.length) + suffix;
62  },
63
64  /**
65   * Remove HTML tags from string
66   * @param {string} str
67   * @returns {string}
68   */
69  stripHtml: function(str) {
70    if (!str) return '';
71
72    return str.replace(/<[^>]*>/g, '');
73  },
74
75  /**
76   * Escape HTML special characters
77   * @param {string} str
78   * @returns {string}
79   */
80  escapeHtml: function(str) {
81    if (!str) return '';
82
83    var map = {
84      '&': '&amp;',
85      '<': '&lt;',
86      '>': '&gt;',
87      '"': '&quot;',
88      "'": '&#039;'
89    };
90
91    return str.replace(/[&<>"']/g, function(char) {
92      return map[char];
93    });
94  },
95
96  /**
97   * Mask sensitive information (e.g., credit card, SSN)
98   * @param {string} str
99   * @param {number} visibleChars - Number of chars to show at end
100   * @param {string} maskChar - Character to use for masking
101   * @returns {string}
102   */
103  mask: function(str, visibleChars, maskChar) {
104    if (!str) return '';
105
106    visibleChars = visibleChars || 4;
107    maskChar = maskChar || '*';
108
109    if (str.length <= visibleChars) {
110      return str;
111    }
112
113    var masked = '';
114    for (var i = 0; i < str.length - visibleChars; i++) {
115      masked += maskChar;
116    }
117
118    return masked + str.substring(str.length - visibleChars);
119  },
120
121  /**
122   * Extract numbers from string
123   * @param {string} str
124   * @returns {string} Numbers only
125   */
126  extractNumbers: function(str) {
127    if (!str) return '';
128
129    return str.replace(/\D/g, '');
130  },
131
132  /**
133   * Format phone number
134   * @param {string} phone
135   * @param {string} format - 'us', 'international'
136   * @returns {string}
137   */
138  formatPhone: function(phone, format) {
139    if (!phone) return '';
140
141    var digits = this.extractNumbers(phone);
142    format = format || 'us';
143
144    if (format === 'us' && digits.length === 10) {
145      return '(' + digits.substring(0, 3) + ') ' +
146             digits.substring(3, 6) + '-' +
147             digits.substring(6);
148    }
149
150    if (format === 'international' && digits.length === 11) {
151      return '+' + digits.substring(0, 1) + ' (' +
152             digits.substring(1, 4) + ') ' +
153             digits.substring(4, 7) + '-' +
154             digits.substring(7);
155    }
156
157    return phone;  // Return original if can't format
158  },
159
160  /**
161   * Slugify string (URL-friendly)
162   * @param {string} str
163   * @returns {string}
164   */
165  slugify: function(str) {
166    if (!str) return '';
167
168    return str
169      .toLowerCase()
170      .replace(/[^\w\s-]/g, '')  // Remove special chars
171      .replace(/[\s_]+/g, '-')    // Replace spaces/underscores with hyphens
172      .replace(/^-+|-+$/g, '');   // Remove leading/trailing hyphens
173  },
174
175  /**
176   * Generate random string
177   * @param {number} length
178   * @param {string} charset - 'alphanumeric', 'alpha', 'numeric', 'hex'
179   * @returns {string}
180   */
181  random: function(length, charset) {
182    length = length || 10;
183    charset = charset || 'alphanumeric';
184
185    var chars = {
186      alphanumeric: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
187      alpha: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
188      numeric: '0123456789',
189      hex: '0123456789abcdef'
190    };
191
192    var charSet = chars[charset] || chars.alphanumeric;
193    var result = '';
194
195    for (var i = 0; i < length; i++) {
196      var randomIndex = Math.floor(Math.random() * charSet.length);
197      result += charSet.charAt(randomIndex);
198    }
199
200    return result;
201  },
202
203  /**
204   * Check if string is valid email
205   * @param {string} email
206   * @returns {boolean}
207   */
208  isValidEmail: function(email) {
209    if (!email) return false;
210
211    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
212    return emailRegex.test(email);
213  },
214
215  /**
216   * Pluralize word based on count
217   * @param {number} count
218   * @param {string} singular
219   * @param {string} plural - Optional, defaults to singular + 's'
220   * @returns {string}
221   */
222  pluralize: function(count, singular, plural) {
223    plural = plural || singular + 's';
224    return count === 1 ? singular : plural;
225  },
226
227  /**
228   * Calculate string similarity (Levenshtein distance)
229   * @param {string} str1
230   * @param {string} str2
231   * @returns {number} Similarity percentage (0-100)
232   */
233  similarity: function(str1, str2) {
234    if (!str1 || !str2) return 0;
235    if (str1 === str2) return 100;
236
237    var longer = str1.length > str2.length ? str1 : str2;
238    var shorter = str1.length > str2.length ? str2 : str1;
239
240    if (longer.length === 0) return 100;
241
242    var distance = this._levenshteinDistance(longer, shorter);
243    return ((longer.length - distance) / longer.length) * 100;
244  },
245
246  /**
247   * Calculate Levenshtein distance between two strings
248   * @private
249   */
250  _levenshteinDistance: function(str1, str2) {
251    var matrix = [];
252
253    for (var i = 0; i <= str2.length; i++) {
254      matrix[i] = [i];
255    }
256
257    for (var j = 0; j <= str1.length; j++) {
258      matrix[0][j] = j;
259    }
260
261    for (var i = 1; i <= str2.length; i++) {
262      for (var j = 1; j <= str1.length; j++) {
263        if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
264          matrix[i][j] = matrix[i - 1][j - 1];
265        } else {
266          matrix[i][j] = Math.min(
267            matrix[i - 1][j - 1] + 1,  // substitution
268            matrix[i][j - 1] + 1,      // insertion
269            matrix[i - 1][j] + 1       // deletion
270          );
271        }
272      }
273    }
274
275    return matrix[str2.length][str1.length];
276  },
277
278  type: 'StringUtils'
279};

How to Use

1. Create a new Script Include named 'StringUtils' 2. Leave 'Client callable' unchecked 3. Copy the code above 4. Use in Business Rules or Background Scripts: var utils = new StringUtils(); var title = utils.toTitleCase('hello world'); // 'Hello World' var slug = utils.slugify('My Blog Post!'); // 'my-blog-post' var masked = utils.mask('1234567890', 4); // '******7890'

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts