CLiown CLiown - 4 months ago 26
Javascript Question

Replace last occurence of character in string

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


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

This will remove the last underscore:

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

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

var str = 'a_b_c', replacement = '!';
str = str.replace(/_([^_]*)$/,replacement+'$1'); //a_b!c