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

时间:2016-07-26 19:14:07

标签: javascript jquery arrays replace

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

我写这段代码但只转换最后一个值(古巴到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 {}
  } 
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:3)

您正在使用最新更改覆盖结果。 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')
);

答案 1 :(得分:1)

虽然您已经接受了答案,但我认为我提供的替代方案可能比原始方法更具响应性,当窗口调整为宽度时,将显示缩写文本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());
    })
  }
});

&#13;
&#13;
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());
    })
  }
});
&#13;
<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>
&#13;
&#13;
&#13;

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

&#13;
&#13;
@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;
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

JS Fiddle demo

答案 2 :(得分:0)

在行中: return Object.keys(fullname).filter(key =&gt; fullname [key] === abbrevname).shift();

使用此参数的过滤器:=&gt;如果删除“&gt;”会导致错误符号响应工作完美!!

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>