【问题标题】:how to shorten filter function with replace and split?如何通过替换和拆分来缩短过滤器功能?
【发布时间】:2021-03-16 11:11:44
【问题描述】:

我将过滤函数与replace() 和split() 结合使用。看起来像这样

jQuery('table .abc').filter((i, el) => jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] + ' ' + jQuery(el).text().replace('a', 'b').split(' ')[1]))

有没有办法缩短它,这样我就不必使用相同的替换和拆分功能两次?因为我只需要将 [0] 和 [1] 结合起来。

【问题讨论】:

  • 题外话:您似乎错误地使用了.filter(),应该是.each()。你也不需要.each,因为你可以使用$(select).text(function(i, text) { return text.replace....text

标签: javascript jquery filter replace split


【解决方案1】:

为了缩短你的代码

jQuery('table .abc').filter((i, el) => 
    jQuery(el).text(jQuery(el).text().replace('a', 'b').split(' ')[0] 
                    + ' ' 
                    + jQuery(el).text().replace('a', 'b').split(' ')[1]))

您可以将overload 用于.text(),它接受一个函数并为选择中的每个元素调用该函数(这是您正在做的,但更简洁)。

您似乎只使用了前两个词,您也可以使用.slice(0,1)giving:

$("table .abc").text((i,txt) => txt.replace("a","b").split(" ").slice(0, 2).join(" ") );

工作示例:

$("table .abc").text((i, txt) => txt.replace("a", "b").split(" ").slice(0, 2).join(" "));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class='abc'>This is more than two words</td>
  </tr>
  <tr>
    <td class='abc'>Here is a second line</td>
  </tr>
  <tr>
    <td class='abc'>OneWord</td>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2018-10-31
    • 2015-04-12
    • 1970-01-01
    • 2021-01-20
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多