Skip to content
Advertisement

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]);

Advertisement

Answer

$ 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');
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement