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
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)
String.replace only replaces the first occurence. To replace them all, add the "g" flag for "global". You can also use character groups and the +operator (one or more) to match chains of characters:
aString.replace("[,\s]+", "*", "g");
This will replace all chains of commas and whitespaces with a *
.
Try this out to remove all spaces and commas, then replace with *.
Myname= myname.replace(/[,\s]/,"*")
Editted as removing 'at least two items' from the pattern. But to have at least on item.
Myname= myname.replace(/([,\s]{1,})/,"*")
Reference: on Rublar. However you are better off with regexpal as per m.buettner :)