Jamesil Jamesil - 1 year ago 121
Javascript Question

Replace Last Character of String

I want to replace the last character in a string with a word.

Eg, 'Flight 12345 A' and I want it to look like 'Flight 12345 Auckland'
The last character can also be W, C, D, Q which stand for different city names.

How can I go about achieving this with js / jQuery??

Thanks heaps in advance!

Answer Source

You can define a map of the different city names and then do the replacement by passing a function as callback to the replace function :

var airports = {
     A: 'Auckland',
     C: 'City2'
var str2 = str.replace(/\w$/, function(l) { return airports[l] });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download