Replace the Last Comma in a String Using Regular Expression

Replace the last comma in a string using Regular Expression

Use greediness to achieve this:

$text = preg_replace('/(.*),/','$1 and',$text)

This matches everything to the last comma and replaces it through itself w/o the comma.

How to replace last comma in string with and using php?

To replace only the last occurrence, I think the better way is:

$likes = 'Apple, Samsung, Microsoft';
$likes = substr_replace($likes, ' and', strrpos($likes, ','), 1);

strrpos finds the position of last comma, and substr_replace puts the desired string in that place replacing '1' characters in this case.

Remove last comma (and possible whitespaces after the last comma) from the end of a string

This will remove the last comma and any whitespace after it:

str = str.replace(/,\s*$/, "");

It uses a regular expression:

  • The / mark the beginning and end of the regular expression

  • The , matches the comma

  • The \s means whitespace characters (space, tab, etc) and the * means 0 or more

  • The $ at the end signifies the end of the string

Replace final comma in a string with and

You probably want

,(?=[^,]+$)

for example:

"1, 2, 3, 4".replace(/,(?=[^,]+$)/, ', and');

(?=[^,]+$) checks that there are no more commas after this comma. (?!.*,) would also work.

You can even check there isn't already an and:

,(?!\s+and\b)(?=[^,]+$)

Working example: https://regex101.com/r/aE2fY7/2

Replace last comma separated value by another using regex

You can use replace() with regex /,[^,]+$/ to match the last string

var str = "a,b,c,d,e,old";var res = str.replace(/,[^,]+$/, ",new");// or you can just use// var res = str.replace(/[^,]+$/, "new");document.write(res);

Replace last instance of comma with 'and' in a string

I think the replaceFirst is better than replaceAll for you because you want to replace only once not all, and it run faster than replaceAll.

  1. using ${number} to capturing groups.

    "a, b, c".replaceFirst(",([^,]+)$", " and$1"); // return "a, b and c"
  2. using positive lookahead:

    "a, b, c".replaceFirst(",(?=[^,]+$)", " and"); // return "a, b and c"

How to remove the last comma from each line in a string?

This is not too good in terms of performance if your string is very long, but it should do

"\n".join(x[:-1] for x in output.splitlines())


Related Topics



Leave a reply



Submit