DEV Community

fiona
fiona

Posted on

3 2

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs