【问题标题】:How to split a string and get last match in jQuery?如何在jQuery中拆分字符串并获取最后一个匹配项?
【发布时间】:2012-11-24 03:22:00
【问题描述】:

我有这样的字符串

This is ~test content ~ok ~fine.

我想得到"fine",它位于特殊字符~ 之后,并且使用jQuery 位于字符串中的最后一个位置。

【问题讨论】:

    标签: jquery split match


    【解决方案1】:

    您可以使用 [substring()][1] 和 [lastIndexOf()][2] 的组合来获取最后一个元素。

    str = "~test content ~thanks ok ~fine";    
    strFine =str.substring(str.lastIndexOf('~'));
    console.log(strFine );

    您可以使用 [split()][4] 将字符串转换为数组并获取最后一个索引处的元素,最后一个索引是length of array - 1,因为数组是从零开始的索引。

    str = "~test content ~thanks ok ~fine";    
    arr = str.split('~');
    strFile = arr[arr.length-1];
    console.log(strFile );

    或者,只需在拆分后得到的数组上调用 pop

    str = "~test content ~thanks ok ~fine";    
    console.log(str.split('~').pop());

    【讨论】:

    • 第一种方法不能真正使用我的路径,保留文件名中的最后一个“\”.. 但第二种方法是正确的。谢谢!
    【解决方案2】:

    只需使用纯 JavaScript:

    var str = "This is ~test content ~thanks ok ~fine";
    var parts = str.split("~");
    var what_you_want = parts.pop();
    // or, non-destructive:
    var what_you_want = parts[parts.length-1];
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2011-03-10
      • 2016-09-20
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多