【问题标题】:How to find the index of a character, searching from right to left?如何找到一个字符的索引,从右到左搜索?
【发布时间】:2022-10-30 22:50:49
【问题描述】:

是否有 JavaScript 函数可以搜索字符串中的字符(如 string.indexOf),但从右到左搜索?

【问题讨论】:

标签: javascript string


【解决方案1】:

这为字符串添加了一个函数。

String.prototype.indexOfRTL = function(search) {
  return (this.length - 1) - [...this].reverse().join("").indexOf(search);
}

例如,现在使用 "Hello There!".indexOfRTL("e") 将得到 10。

【讨论】:

  • 还是只是标准的lastIndexOf 方法?
  • 这种方式的问题是这会创建 3 个字符串副本,而实际上这只需要迭代。
猜你喜欢
  • 1970-01-01
  • 2012-07-25
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多