To remove white spaces from a field

Poorva Bhawsar
Mega Sage

Hi Community,

 

I have a BR using which i am removing the spaces from a field. First the data is getting being loaded via scheduled job. Once its loaded an after insert/update BR will work and it will remove the spaces from that field.

 

Here is the code, i thought it was working fine in background script but now it didnt removed spaces from 2 records.

var record = new GlideRecord('xyz');
    record.query();
    while (record.next()) {
 
        record.abc = record.abc.toString().replace('ABCD', '');
        record.abc = record.abc.toString().replace(/ /g, '');
        record.setWorkflow(false); //Do not run business rules
        record.autoSysFields(false); //Do not update system fields
        record.update();
    }
 
Let me know is there any change required in the code and why it didnt removed spaces for 2 records.
 
Thanks
1 ACCEPTED SOLUTION

@Poorva Bhawsar 

okay got it

then do this and it will replace 1 or more whitespaces

record.abc = record.abc.toString().replace(/\s+/g, '');

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

5 REPLIES 5

Runjay Patel
Giga Sage

Hi @Poorva Bhawsar ,

 

Try using below code.

var record = new GlideRecord('xyz');
record.query();

while (record.next()) {
    if (record.abc) { // Ensure the field is not null
        var updatedValue = record.abc.toString()
            .replace(/ABCD/gi, '') // Case-insensitive removal of 'ABCD'
            .replace(/ /g, '');    // Remove all spaces

        // Update only if there's a change to prevent redundant saves
        if (record.abc.toString() !== updatedValue) {
            record.abc = updatedValue;
            record.setWorkflow(false); // Skip business rules
            record.autoSysFields(false); // Skip system field updates
            record.update();
        }
    }
}

 

-------------------------------------------------------------------------

If you found my response helpful, please consider selecting "Accept as Solution" and marking it as "Helpful." This not only supports me but also benefits the community.


Regards
Runjay Patel - ServiceNow Solution Architect
YouTube: https://www.youtube.com/@RunjayP
LinkedIn: https://www.linkedin.com/in/runjay

-------------------------------------------------------------------------

Here in this Video, I have covered the Custom Application Pattern Troubleshooting and configuration Thank you for visiting my channel. Here, I'll share various technical knowledge. Feel free to reach out to me directly for any Service Now-related queries. Your support encourages me to consistently