Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 742
Zed Avatar asked May 31 '14 12:05

Zed


People also ask

How do you remove the first comma from a string?

Using the String. We call replace with /^,/ to replace the leading comma with an empty string. And so newString is the same as before.

Which function is used to find the first instance of comma in a string?

We can use the find() function in Python to find the first occurrence of a substring inside a string.


3 Answers

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.

like image 115
Barmar Avatar answered Oct 04 '22 14:10

Barmar


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(',', '');
like image 37
falsetru Avatar answered Oct 04 '22 14:10

falsetru


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)
like image 39
ridgerunner Avatar answered Oct 04 '22 15:10

ridgerunner