Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Using regex to make special characters disappear except when it is a dash. How do you do that?

snow_beginner
Giga Guru

Hi, so I have story where the name of a field is converted to n alphanumeric label with the following requirements:

 

Remove any special characters
Replace spaces with -
If there are any multiple - (e.g. – or — replace with just - )
Force uppercase the string
Force uppercase the AL number
Build the string as AL01234_APP-NAME

 

I have made a before business rule for the field with the following code

(function executeRule(current, previous /*null when async*/) {

	// Add your code here
	var name = current.name;
	var app_id = current.u_application_id;
	var output = transformString(name,app_id);
	current.u_alphanumeric_label = output;

})(current, previous);

function transformString(nameString, alNumber) {
  // Step 1: Remove special characters
  const regex = /[^a-zA-Z0-9\s]/g;
  var transformedString = nameString.replace(regex, '');

  // Step 2: Replace space with -
  transformedString = transformedString.replace(/\s+/g, '-');

  // Step 3: Replace multiple '-' with a single '-'
 transformedString = transformedString.replace(/-{1,}/g, '-');

  // Step 4: Change the string into uppercase
  transformedString = transformedString.toUpperCase();
  
  // Step 5: Change the alNumber into uppercase and append with transformed name string
  
  return alNumber.toUpperCase() +'_'+ transformedString;
}

This works fine except for requirement 3 where - or mutliple ---- should be changed to just - 

Can anyone help me with that, for the above code when it checks for special characters it includes - in them and thus removes them, is there a way to work around that so that a single - is fine and multiple ---- turn to -

1 ACCEPTED SOLUTION

Correct. All the '-' signs are removed earlier within your step 1, since these are considered to be special characters.

You can modify your step 1 and include '-' in your existing regex.

Something like below:

// Step 1: Remove special characters
  const regex = /[^a-zA-Z0-9\s\-]/g;
  var transformedString = nameString.replace(regex, '');

View solution in original post

6 REPLIES 6

Correct. All the '-' signs are removed earlier within your step 1, since these are considered to be special characters.

You can modify your step 1 and include '-' in your existing regex.

Something like below:

// Step 1: Remove special characters
  const regex = /[^a-zA-Z0-9\s\-]/g;
  var transformedString = nameString.replace(regex, '');

Thanks so much, that has resolved the problem!