I have a string that looks like this: \"Doe, John, A\" (lastname, firstname, middle initial).
I\'m trying to write a regular expression that converts the string into \"D
Yes, there is. Use the replace
function with a regex instead. That has a few advantages. Firstly, you don't have to call it twice anymore. Secondly it's really easy to account for an arbitrary amount of spaces and an optional comma:
aString = aString.replace(/[ ]*,[ ]*|[ ]+/g, '*');
Note that the square brackets around the spaces are optional, but I find they make the space characters more easily readable. If you want to allow/remove any kind of whitespace there (tabs and line breaks, too), use \s
instead:
aString = aString.replace(/\s*,\s*|\s+,/g, '*');
Note that in both cases we cannot simply make the comma optional, because that would allow zero-width matches, which would introduce a *
at every single position in the string. (Thanks to CruorVult for pointing this out)