I am having two strings separated by multiple commas. I need to retain only a single comma between the two strings. for example I have as follows var cptCode = G1077,,,,,,,,,,D3456 so after removing multiple commas, I will have like this : var cptCode = G1077,D3456 The user can enter 2 commas or 5 commas between the two strings. Maximum number of commas between the two strings will be 10. I request the members to let me know how to achieve this.


That's basic JavaScript. It doesn't really even matter how many commas are there, 2 or a million. Just replace them all with a single instance:

cptCode = cptCode.replace(/,+/g,',');

Where /,+/g is a Regular Expression meaning "find a comma (,) followed by any further commas (+), globally within the string (/.../g)." Each match will then be "replaced" with just a single comma (the second parameter).


Simple solution:

Add them to a list, then join the list.

List<String> values = <field>.split( ',' );
String result = String.join( values, ',' );
  • 1
    JavaScript, not Apex. Also, you'd end up with the same commas you had before. The correct version would have been: <field>.split(',+'). – sfdcfox Apr 3 '20 at 3:11
  • you're right, of course your answer would be simplest. – Ronnie Apr 3 '20 at 3:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.