CLiown CLiown - 1 year ago 92
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download