使用JS/JQuery将大文本转换为缩写或短字符串

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

本文关键字:缩写 字符串 转换 文本 JS JQuery 使用      更新时间:2023-09-26

我需要将这些大字符串转换为缩写(短)字符串文本

我写了这个代码,但只转换最后一个值(古巴到古巴)

你能帮我吗

  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')
);

虽然你已经接受了一个答案,但我想我会提供一个替代方案,它可能比你原来的方法更具响应性,当窗口的宽度调整到480px以下时,它会显示缩写文本,而当窗口的宽度调整到大于或等于480px时,它将恢复原始文本:

// this function takes an object (the 'haystack') within which
// we search for the supplied value (the 'needle'):
function getKeyFromValue(haystack, needle) {
  // here we retrieve the keys of the supplied Object using
  // Object.keys, which returns an Array of those keys:
  return Object.keys(haystack)
    // here we filter the Array of keys, using an Arrow
    // function, to retain only the key(s) for which
    // the value stored in the Object with the current
    // key is exactly equal to the supplied needle to
    // search for:
    .filter(key => haystack[key] === needle)
    // we then take the first element of the retained
    // Array of keys, and return that to the calling
    // context:
    .shift();
}
// an object tying full names to abbreviated names:
var locationAbbreviations = {
  'Cancún': 'CUN',
  'Cuba': 'CUB',
  'Guadalajara': 'GDL',
  'Monterrey': 'MTY',
  'Tijuana': 'TIJ',
  'Toluca': 'TLC'
};
// binding the text-updates to the resize event(s) of
// the window:
$(window).resize(function() {
  // caching the elements:
  var elems = $('li a');
  // if the window width is less than 480px:
  if ($(this).width() < 480) {
    // we update the text of each of the found
    // elements, using the text() method's
    // anonymous function:
    elems.text(function(i, text) {
      // i:    the first argument, is the index of the
      //       current element in the jQuery collection
      //       element nodes.
      // text: the second argument, the current text
      // of the current element.
      // here we look up the abbreviation by using
      // the trimmed text of the current element 
      // (trimming removes leading and trailing
      // white-space from the String) as the key
      // with which to search in the
      // locationAbbreviations Object; if no value is
      // returned the response will be undefined
      // (falsey) so instead the original text will be
      // returned:
      return locationAbbreviations[text.trim()] || text;
    });
  } else {
    // otherwise, we instead use the text() method
    // and its anonymous function to return the
    // result of calling a function:
    elems.text(function(i, text) {
      // here we call the named function, supplying
      // both the Object ('haystack') and trimmed
      // string of text from the current element
      // ('needle'):
      return getKeyFromValue(locationAbbreviations, text.trim());
    })
  }
});

function getKeyFromValue(haystack, needle) {
  return Object.keys(haystack).filter(key => haystack[key] === needle).pop();
}
var locationAbbreviations = {
  'Cancún': 'CUN',
  'Cuba': 'CUB',
  'Guadalajara': 'GDL',
  'Monterrey': 'MTY',
  'Tijuana': 'TIJ',
  'Toluca': 'TLC'
};
$(window).resize(function() {
  var elems = $('li a');
  if ($(this).width() < 480) {
    elems.text(function(i, text) {
      return locationAbbreviations[text.trim()] || text;
    });
  } else {
    elems.text(function(i, text) {
      return getKeyFromValue(locationAbbreviations, text.trim());
    })
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Tijuana</a>
  </li>
  <li><a href="#">Cancún</a>
  </li>
  <li><a href="#">Cuba</a>
  </li>
  <li><a href="#">Guadalajara</a>
  </li>
  <li><a href="#">Monterrey</a>
  </li>
  <li><a href="#">Tijuana</a>
  </li>
  <li><a href="#">Toluca</a>
  </li>
</ul>

JS Fiddle。

或者,这可以通过简单的HTML和CSS来实现,尽管有一些附加HTML,例如:

<ul>
  <li><a href="#">
    <!-- element to show when width > 480px,
         and hide when width < 480 -->
    <span class="full">Tijuana</span>
    <!-- element to show when width < 480px,
         and hide when width > 480px -->
    <span class="abbreviated">TIJ</span>
  </a></li>
  <!-- repeated lines of the same format removed
       for brevity -->
</ul>

为了实现这种行为,我们可以选择使用简单的媒体查询,而不是JavaScript:

/* when content is displayed on a screen,
   and the maximum width of that screen/
   viewport is 479px (you specified
   '<480px' in your posted question): */
@media only screen and (max-width: 479px) {
  /* we hide the element(s) found with this
     selector: */
  li a span.full {
    display: none;
  }
  /* and show the element(s) found with
     this selector: */
  li a span.abbreviated {
    display: inline;
  }
}
/* The inverse of the above, selecting only
   devices with a screen, and with the minimum
   width of that screen/viewport being 480px: */
@media only screen and (min-width: 480px) {
  /* show these elements: */
  li a span.full {
    display: inline;
  }
  /* hide these elements: */
  li a span.abbreviated {
    display: none;
  }
}

@media only screen and (max-width: 479px) {
  li a span.full {
    display: none;
  }
  li a span.abbreviated {
    display: inline;
  }
}
@media only screen and (min-width: 480px) {
  li a span.full {
    display: inline;
  }
  li a span.abbreviated {
    display: none;
  }
}
<ul>
  <li><a href="#"><span class="full">Tijuana</span><span class="abbreviated">TIJ</span></a>
  </li>
  <li><a href="#"><span class="full">Cancún</span><span class="abbreviated">CUN</span></a>
  </li>
  <li><a href="#"><span class="full">Cuba</span><span class="abbreviated">CUB</span></a>
  </li>
  <li><a href="#"><span class="full">Guadalajara</span><span class="abbreviated">GDL</span></a>
  </li>
  <li><a href="#"><span class="full">Monterrey</span><span class="abbreviated">MTY</span></a>
  </li>
  <li><a href="#"><span class="full">Tijuana</span><span class="abbreviated">TIJ</span></a>
  </li>
  <li><a href="#"><span class="full">Toluca</span><span class="abbreviated">TLC</span></a>
  </li>
</ul>

JS Fiddle演示。

行中:return Object.keys(fullname).filter(key=>fullname[key]===缩写名称).shift();

带有此参数的过滤器:=>如果删除">"符号,将导致错误-响应效果完美!!

return Object.keys(fullname).filter(key=fullname[key]===abbrevname).shift();

function getKeyFromValue(haystack, needle) {
  return Object.keys(haystack).filter(key => haystack[key] === needle).pop();
}
var locationAbbreviations = {
  'Cancún': 'CUN',
  'Cuba': 'CUB',
  'Guadalajara': 'GDL',
  'Monterrey': 'MTY',
  'Tijuana': 'TIJ',
  'Toluca': 'TLC'
};
$(window).resize(function() {
  var elems = $('li a');
  if ($(this).width() < 480) {
    elems.text(function(i, text) {
      return locationAbbreviations[text.trim()] || text;
    });
  } else {
    elems.text(function(i, text) {
      return getKeyFromValue(locationAbbreviations, text.trim());
    })
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Tijuana</a>
  </li>
  <li><a href="#">Cancún</a>
  </li>
  <li><a href="#">Cuba</a>
  </li>
  <li><a href="#">Guadalajara</a>
  </li>
  <li><a href="#">Monterrey</a>
  </li>
  <li><a href="#">Tijuana</a>
  </li>
  <li><a href="#">Toluca</a>
  </li>
</ul>