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 t
Solution 1:
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.
Solution 2:
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(',', '');
Solution 3:
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)
Solution 4:
you could also use a lookahead like so ^(.*?),(?=.*,)
and replace w/ $1
Demo
Solution 5:
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(/,(?=[^,]*,)/, '');
Post a Comment for "Remove First Occurrence Of Comma In A String"