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 "Doe*John*A".
However, I have to take into account all spaces for this string so "Doe , John , A" would still convert into "Doe*John*A".
ALSO, the string "Doe John A" should convert into "Doe*John*A".
I started writing this, but I think I'm stuck on the spaces & the possibility of the user not supplying the commas.
Here's what I have:
var myString = "John, Doe, A";
var myOtherString = "John Doe A";
var myFunction = function (aString) {
aString = aString.replace(", ", "*");
aString = aString.replace(", ", "*");
return aString;
};
These should both return "Doe*John*A"
.
I think I'm repeating myself too much in this function. I'm also not taking into account the possibility that no commas will be provided.
Is there a better way to do this?
If you want to replace all non-word characters try this:
str.replace(/\W+/g, '*');
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With