Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  122] [ 1]  / answers: 1 / hits: 133371  / 13 Years ago, thu, march 31, 2011, 12:00:00

Is there an easy way in javascript to replace the last occurrence of an '_' (underscore) in a given string?


More From » javascript

 Answers
2

You don't need jQuery, just a regular expression.



This will remove the last underscore:





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





This will replace it with the contents of the variable replacement:





var str = 'a_b_c',
replacement = '!';

console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c




[#92994] Wednesday, March 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
farrahsavannahl

Total Points: 418
Total Questions: 108
Total Answers: 90

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
;