gravityboy
gravityboy

Reputation: 817

regex replace just the last charater of a string

This should be an easy one and I couldn't find it anywhere. How do I replace just the last character of a string with a char from an array?

str1 = str1.replace(?????, myArray[b]);

Upvotes: 4

Views: 16171

Answers (2)

Jan
Jan

Reputation: 8131

$ matches the end of a string, . matches any character

const replaceLast = (str, replace) => str.replace(/.$/, replace);
replaceLast('cat', 'r');

But you should probably use string functions for this:

const replaceLast = (str, replace) => str.slice(0, -1) + replace;
replaceLast('cat', 'r');

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could try the substring method:

str1 = str1.substring(0, str1.length - 1) + myArray[b];

Upvotes: 9

Related Questions