DEV Community

fiona
fiona

Posted on

replace the last comma to period in string

To slightly modify a string, like replacing its first character to capital or last character from comma to period, there are two ways to achieve.

use replace() with regex

There are two things worth notice:

  • without using regular expression, only the first-matched substring will be replaced.
  • replace() function returns a new string and left the old string unchanged.
// replace the last comma to period
let names = "anne, ben, carol, dennis, evans,";
names = names.replace(/,$/, '.');
// anne, ben, carol, dennis, evans.
Enter fullscreen mode Exit fullscreen mode

use slice() and append

// replace the last comma to period
let names = "anne, ben, carol, dennis, evans,";
names = names.slice(0, -1) + '.';
// anne, ben, carol, dennis, evans.
Enter fullscreen mode Exit fullscreen mode

slice(indexStart, indexEnd) and substring(indexStart, indexEnd) are almost identical with some slight differences:

  • indexEnd is optional in both functions, if not specified it would extract to the end of the string. Otherwise, it is the first character to exclude.
  • If value is less than 0 or NaN, substring() would consider 0. slice() would consider NaN 0, and negative values count backwards from the end.
  • If value is greater than stringName.length, it would consider stringName.length in both functions.
  • substring() swap the arguements if indexStart is greater than indexEnd, slice() returns an empty string.

Top comments (0)