Zed
Zed

Reputation: 5931

Remove first occurrence of comma in a string

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 return instead:

"some text1 some text2, some tex3"

So, the function should only look if there's more than one comma, and if there is, it should remove the first occurrence. This could be probably solved with the regex but I don't know how to write it, any ideas ?

Upvotes: 21

Views: 40645

Answers (5)

falsetru
falsetru

Reputation: 368954

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(',', '');

Upvotes: 20

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

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(/,(?=[^,]*,)/, '');

Upvotes: 1

alpha bravo
alpha bravo

Reputation: 7948

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

Upvotes: 2

ridgerunner
ridgerunner

Reputation: 34385

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)

Upvotes: 2

Barmar
Barmar

Reputation: 780798

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.

Upvotes: 34

Related Questions