Jamesil
Jamesil

Reputation: 183

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!

Upvotes: 0

Views: 699

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382454

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] });

Upvotes: 2

Related Questions