Reputation: 817
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
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
Reputation: 1038710
You could try the substring
method:
str1 = str1.substring(0, str1.length - 1) + myArray[b];
Upvotes: 9