Replace the Last Comma with an & Sign

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

how to replace last comma with and

var test = "Service Control Manager repeated 5 times, " +
"Microsoft-Windows-DistributedCOM repeated 2 times, " +
"Control Manager repeated 6 times.";
var lastComma = test.LastIndexOf(',');
if (lastComma != -1) test = test.Remove(lastComma, 1).Insert(lastComma, " and");

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 the last comma with an & sign

Pop off the last element, implode the rest together then stick the last one back on.

$bedroom_array = array('studio', 'one_bed', 'two_bed', 'three_bed', 'four_bed');
$last = array_pop($bedroom_array);
$string = count($bedroom_array) ? implode(", ", $bedroom_array) . " & " . $last : $last;

Convert & to the entity & if necessary.

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.

Replace last comma in character with &

One option is stri_replace_last from stringi

library(stringi)
stri_replace_last(x, fixed = ',', ' &')
#[1] "char1, char2 & char3"

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"


Related Topics



Leave a reply



Submit