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?
JavaScript
x
2
1
str1 = str1.replace(?????, myArray[b]);
2
Advertisement
Answer
$
matches the end of a string, .
matches any character
JavaScript
1
3
1
const replaceLast = (str, replace) => str.replace(/.$/, replace);
2
replaceLast('cat', 'r');
3
But you should probably use string functions for this:
JavaScript
1
3
1
const replaceLast = (str, replace) => str.slice(0, -1) + replace;
2
replaceLast('cat', 'r');
3