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