我正在特别寻找 javascript,但我想这个问题在任何语言中都是一样的。 indexOf 函数允许我们指定要查找的内容以及从哪里开始。然后它从开始位置向下搜索字符串。有没有办法搜索字符串?
IE伪代码:
str = "Hello this is a string, this is how I would like to search this string."
str.indexOf(lookFor = "this", startPosition = indexOf(how), lookUp = true)
在这种情况下,函数应该返回就在“how”之前的“this”。不是字符串开头的那个,也不是"how"后面的那个。
最佳答案
要在 "how"
之前搜索,切片:
str.slice(0, str.indexOf("how")).indexOf("this")
如果你想得到一个字符串在“how”之前的最后一次出现,将它与lastIndexOf
结合起来:
str.slice(0, str.indexOf("how")).lastIndexOf("this")
关于javascript - indexOf,向上搜索字符串而不是向下搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18825620/