Regex replace all commas with value

前端 未结 4 1707
长发绾君心
长发绾君心 2021-02-13 12:36

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

4条回答
  •  旧巷少年郎
    2021-02-13 13:03

    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)

提交回复
热议问题