Remove first occurrence of comma in a string

后端 未结 5 1440
甜味超标
甜味超标 2020-12-18 20:51

I am looking for a way to remove the first occurrence of a comma in a string, for example

\"some text1, some tex2, some text3\"

should retu

相关标签:
5条回答
  • 2020-12-18 21:38

    This will do it:

    if (str.match(/,.*,/)) { // Check if there are 2 commas
        str = str.replace(',', ''); // Remove the first one
    }
    

    When you use the replace method with a string rather than an RE, it just replaces the first match.

    0 讨论(0)
  • 2020-12-18 21:47

    you could also use a lookahead like so ^(.*?),(?=.*,) and replace w/ $1
    Demo

    0 讨论(0)
  • 2020-12-18 21:54

    String.prototype.replace replaces only the first occurence of the match:

    "some text1, some tex2, some text3".replace(',', '')
    // => "some text1 some tex2, some text3"
    

    Global replacement occurs only when you specify the regular expression with g flag.


    var str = ",.,.";
    if (str.match(/,/g).length > 1) // if there's more than one comma
        str = str.replace(',', '');
    
    0 讨论(0)
  • 2020-12-18 21:54

    A simple one liner will do it:

    text = text.replace(/^(?=(?:[^,]*,){2})([^,]*),/, '$1');
    

    Here is how it works:

    regex = re.compile(r"""
        ^                # Anchor to start of line|string.
        (?=              # Look ahead to make sure
          (?:[^,]*,){2}  # There are at least 2 commas.
        )                # End lookahead assertion.
        ([^,]*)          # $1: Zero or more non-commas.
        ,                # First comma is to be stripped.
        """, re.VERBOSE)
    
    0 讨论(0)
  • 2020-12-18 21:58

    a way with split:

    var txt = 'some text1, some text2, some text3';
    
    var arr = txt.split(',', 3);
    
    if (arr.length == 3)
        txt = arr[0] + arr[1] + ',' + arr[2];
    

    or shorter:

    if ((arr = txt.split(',', 3)).length == 3)
        txt = arr[0] + arr[1] + ',' + arr[2];
    

    If there are less than 3 elements in the array (less than 2 commas) the string stay unchanged. The split method use the limit parameter (set to 3), as soon as the limit of 3 elements is reached, the split method stops.

    or with replace:

    txt = txt.replace(/,(?=[^,]*,)/, '');
    
    0 讨论(0)
提交回复
热议问题