AlonsoCT AlonsoCT - 4 months ago 20
Javascript Question

Convert a large text to abbrevation or short string with JS/JQuery

I need to convert this large strings to a abbrev (short) string text

I write this code but only convert the last value (Cuba to CUB)

Can you help me please?



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 {}
}




Answer

You are overwriting the result with the latest change. Replace returns a string and you need to replace every part. If you assign it to the output, you keep the original text value and do not replace it.

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 {}
  } 

A bit shorter in a single chain

$(this).text(
    $(this).text()
    .replace('Tijuana', 'TIJ')
    .replace('Monterrey', 'MTY')
    .replace('Guadalajara', 'GDL')
    .replace('Toluca', 'TLC')
    .replace('Cancún', 'CUN')
    .replace('Cuba', 'CUB')
);
Comments