代码之家  ›  专栏  ›  技术社区  ›  Nero

如何在最后指定的字符之后获取子字符串?Javascript

  •  2
  • Nero  · 技术社区  · 7 年前

    假设我有以下字符串:

    var text = "A_B_C_190"
    

    我希望能够提取结尾处的数字(最后一个\u1后的最后3个字符)

    我累了:

    text.substr(text.indexOf('_'), -1)
    

    但这给了我零

    2 回复  |  直到 7 年前
        1
  •  1
  •   Faly    7 年前

    您可以使用 string.prototype.split array.prototype.pop :

    var text = "A_B_C_190";
    console.log(text.split('_').pop());
        2
  •  -1
  •   Udayraj Deshmukh    7 年前

    您必须使用lastIndexOf方法。

    var text = "A_B_C_190"
    ans = text.substr(text.lastIndexOf('_')+1)
    console.log(ans)

    如果要将其转换为整数,请使用 parseInt(ans)