我需要将这个大字符串转换为缩写(短)字符串文本
我写这段代码但只转换最后一个值(Cuba 到 CUB)
你能帮帮我吗?
function text_abbrev() {
if ($(window).width() <= 480) {
$('.nav-tabs li a').each(function() {
var text = $(this).text();
$(this).text(text.replace('Tijuana', 'TIJ'));
$(this).text(text.replace('Monterrey', 'MTY'));
$(this).text(text.replace('Guadalajara', 'GDL'));
$(this).text(text.replace('Toluca', 'TLC'));
$(this).text(text.replace('Cancún', 'CUN'));
$(this).text(text.replace('Cuba', 'CUB'));
});
} else {}
}
最佳答案
您正在用最新的更改覆盖结果。 Replace 返回一个字符串,您需要替换每个部分。如果将它分配给输出,则保留原始 text
值并且不会替换它。
function text_abbrev() {
if ($(window).width() <= 480) {
$('.nav-tabs li a').each(function() {
var text = $(this).text();
text = text.replace('Tijuana', 'TIJ');
text = text.replace('Monterrey', 'MTY');
text = text.replace('Guadalajara', 'GDL');
text = text.replace('Toluca', 'TLC');
text = text.replace('Cancún', 'CUN');
$(this).text(text.replace('Cuba', 'CUB'));
});
} else {}
}
单链短一点
$(this).text(
$(this).text()
.replace('Tijuana', 'TIJ')
.replace('Monterrey', 'MTY')
.replace('Guadalajara', 'GDL')
.replace('Toluca', 'TLC')
.replace('Cancún', 'CUN')
.replace('Cuba', 'CUB')
);
关于javascript - 使用 JS/JQuery 将大文本转换为缩写或短字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38598117/