Categories
JavaScript Answers

How to Replace the Last Occurrence of a Character in a String in JavaScript?

Spread the love

To replace the last occurrence of a character in a string in JavaScript, we can use the JavaScript string replace method with a regex.

For instance, we can write:

const str = 'a_b_c';
console.log(str.replace(/_([^_]*)$/, '$1'))

to remove the underscore before the 'c' character.

To do that, we call replace with a regex that searches for the last instance of an underscore with a character after it.

Then in the 2nd argument, we pass in '$1' to remove the underscore from the last instance of the regex match.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.