简体   繁体   English

替换字符串的最后一个字符

[英]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. 例如,“航班12345 A”,我希望它看起来像“航班12345奥克兰”。最后一个字符也可以是W,C,D,Q,代表不同的城市名称。

How can I go about achieving this with js / jQuery?? 如何使用js / jQuery实现此目标?

Thanks heaps in advance! 预先感谢堆积!

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 : 您可以定义不同城市名称的地图,然后通过将函数作为回调传递给replace函数来进行替换

var airports = {
     A: 'Auckland',
     C: 'City2'
     ...
};
var str2 = str.replace(/\w$/, function(l) { return airports[l] });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM