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

snow_beginner
Mega 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

Karan Chhabra6
Mega Sage
Mega Sage

Hi @snow_beginner ,

 

Replace the line of code in Step 3 with the line below:

 

 transformedString = transformedString.replace(/-+/g, '-');

 

 

If my answer has helped with your question, please mark it as correct and helpful

 

Thanks!

Hi I tried that and it did not work. It is still removing - all together. 

OlaN
Giga Sage
Giga Sage

Hi,

Try this for your step 3.

 

  // Step 3: Replace multiple '-' with a single '-'
 transformedString = transformedString.replace(/[-]+/, '-');

Hi I tried this and it did not work, it still removed - altogether. I think it is considering - as a special character too and thats why it is removing that.