Regex replace all commas with value

前端 未结 4 1795
长发绾君心
长发绾君心 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 12:57

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

    str.replace(/\W+/g, '*');
    
    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2021-02-13 13:16

    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 *.

    0 讨论(0)
  • 2021-02-13 13:16

    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 :)

    0 讨论(0)
提交回复
热议问题