Replace Field Value using Regex

carlocsa
Kilo Expert

Hi!

I have a field containing a string. For example "servicenow guru". I want to remove the space between "servicenow" and "guru" upon submitting the record.   The value after submit should be "servicenowguru"). How to do this in a catalog client script?

Thanks!

Carlo

1 ACCEPTED SOLUTION

If it is on client script;


var variable = g_form.getValue('variable name');


var variable1 = variable.toString().replace(/\s/g, '').trim();  


g_form.setValue('variable name',variable1);


View solution in original post

8 REPLIES 8

I'm using a catalog client script, so can't use "current".



This is my onSubmit code but not working.



function onSubmit() {



var str = newValue.replace(s/   +/ /g,'');


g_form.setValue('field1',str);



   


}


let's try,



var str = newValue.replace(' ','');


g_form.setValue('field1',str);



OR



if(newValue.indexOf(" ") >= 0)


g_form.setValue('field1',newValue.split(' ').join(''));


Andrew Bettcher
Kilo Sage

Hi,

I have a similar issue on a transform script. We import assets from another system and that sometimes includes single lines with many devices on it. These involve a serial number that contains a single serial number for every device which I receive as a comma separated list. E.G.:

CKM12345, CKM67890, CKM54321 etc.

I split these out and create a separate asset record for each item. I have been able to trim the ", " from the strings and that works great for 99% of the time. However, the source isn't reliable and, occasionally, due to human error or some other issue, I get two spaces after each comma which results in near duplicates in my asset database (i.e. they are near duplicates because one has the serial number only and the other has the serial number preceded by a space. I am trying to eliminate all spaces from the string just in case. 

This is my script (the relevant part of it:

var serialNumberList = source.u_serial_number.toString().split(", ");

serialNumberList = serialNumberList.replace(/\s/g, '').trim();

for(var i=0;i < serialNumberList.length;i++){

var serialNumber = serialNumberList[i];
	

That works in a background script but it doesn't work when I do a test import with double spaced items. The lines are simply rejected from being imported.

I've tried a few things such as:

var serialNumberList = source.u_serial_number.toString().split(", ").replace(/\s/g, '').trim()

for(var i=0;i < serialNumberList.length;i++){

var serialNumber = serialNumberList[i];
	

Any ideas what's going wrong?

 

Andrew Bettcher
Kilo Sage

Aha. A little fiddling and "thinking outside the box" led me to this:

var serialNumberList = source.u_serial_number.toString().split(", ");
	
for(var i=0;i < serialNumberList.length;i++){
		
var serialNumber = serialNumberList[i].replace(/[^a-zA-Z0-9]/g, '');

which worked a treat. 😉