Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace all commas with value

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?

like image 853
Jeff Avatar asked Dec 19 '12 15:12

Jeff


2 Answers

If you want to replace all non-word characters try this:

str.replace(/\W+/g, '*');
like image 128
CruorVult Avatar answered Oct 21 '22 16:10

CruorVult


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)

like image 42
Martin Ender Avatar answered Oct 21 '22 17:10

Martin Ender