繁体   English   中英

检查第一个字符串

[英]Check First Character String

我对这个任务有点困惑。

给定 list="aaabcdefaabc" 和 word="abc"。

您可以看到包含“abc”的列表将使我们的答案为 2 和 9

你能给我一些关于 javascript 的见解吗?

你的意思是这样的吗?

let list="aaabcdefaabc"
matches = list.matchAll("abc")
for (let match of matches) console.log(match.index) // prints 2 and 9

编辑:制作一个 function 返回索引

这个答案的帮助下:

function searchIndices(str,pattern) {
   let matches = str.matchAll(pattern) // Object [RegExp String Iterator]
   matches = [...matches] // convert it to Array
   indices = matches.map(match => match.index) // get index from each match
   return indices
}
let ii = searchIndices("aaabcdefaabc","abc")
console.log(ii)

我不确定我是否理解这个问题。

可以使用 indexOf 和 lastIndexOf 找到索引。

let list="aaabcdefaabc"
console.log(list.indexOf("abc"))
// this print 2

console.log(list.lastIndexOf("abc"))
// this print 9

更多文档可以在这里找到, https://www.w3schools.com/jsref/jsref_lastindexof.asp

这对你有帮助吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM