Skip to content

Commit dc53e35

Browse files
authored
Create removeSpaces.js
Created the js file that contains the logic to clear extra spaces
1 parent 5ad0e8e commit dc53e35

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* Fix Script: Remove Extra Spaces from a Field
3+
*
4+
* Description:
5+
* This script removes leading/trailing spaces and collapses multiple
6+
* consecutive spaces into a single space for a specified field on a specified table.
7+
*
8+
* INSTRUCTIONS:
9+
* 1. Update the tableName and fieldName with the table and field you want to remove spaces from, usually fieldName will be name or short_description
10+
* 2. Set 'processRecords' to false for a preview, set to true to do the updates
11+
*/
12+
13+
(function () {
14+
// Set to true to perform the update, false to just preview the changes
15+
var processRecords = false;
16+
17+
var tableName = 'incident'; // Add your table name
18+
var fieldName = 'short_description'; // Add the field that might contain leading spaces
19+
20+
var recordsUpdated = 0;
21+
22+
if (gs.nil(tableName) || gs.nil(fieldName)) {
23+
gs.print('Please set the table and field name');
24+
return;
25+
}
26+
27+
gs.info('Starting space removal process for table: [' + tableName + '], field: [' + fieldName + ']');
28+
gs.info('Run mode: ' + (processRecords ? 'UPDATE' : 'PREVIEW'));
29+
30+
try {
31+
var gr = new GlideRecord(tableName);
32+
// Only query records where the target field is not empty
33+
gr.addNotNullQuery(fieldName);
34+
gr.query();
35+
36+
while (gr.next()) {
37+
var originalValue = gr.getValue(fieldName);
38+
39+
// Replace all occurrences of 2 or more spaces with a single space and trim leading/trailing whitespace
40+
var cleanedValue = originalValue.replace(/\s\s+/g, ' ').trim();
41+
42+
// Check if the value has actually changed
43+
if (originalValue !== cleanedValue) {
44+
gs.print('Record sys_id: ' + gr.getUniqueValue() + ' (Number: ' + gr.getDisplayValue('number') + ')\n' +
45+
'---> Original: "' + originalValue + '"\n' +
46+
'---> Cleaned: "' + cleanedValue + '"\n'
47+
);
48+
49+
if (processRecords) {
50+
gr.setValue(fieldName, cleanedValue);
51+
gr.setWorkflow(false);
52+
gr.autoSysFields(false);
53+
gr.update();
54+
recordsUpdated++;
55+
}
56+
}
57+
}
58+
59+
gs.print('Space removal process finished.');
60+
if (processRecords) {
61+
gs.info(recordsUpdated + ' records were updated.');
62+
} else {
63+
gs.print('This was a PREVIEW run. No records were updated. To apply changes, set the "processRecords" variable to true.');
64+
}
65+
66+
} catch (e) {
67+
gs.error('An error occurred during the space removal script: ' + e.message);
68+
}
69+
})();

0 commit comments

Comments
 (0)