CLiown CLiown - 1 month ago 7
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?

Answer

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
Comments