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.
-
What have you tried? Where are you stuck? Please take a look at How to Ask and edit your post. – David Reed♦ Apr 3 '20 at 3:00
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, ',' );
-
1JavaScript, 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 -