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 ?
Using the String. We call replace with /^,/ to replace the leading comma with an empty string. And so newString is the same as before.
We can use the find() function in Python to find the first occurrence of a substring inside a string.
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.
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(',', '');
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With