-1

I'm a little bit confused with this task.

given the list="aaabcdefaabc" and word="abc".

You can see that list contain "abc" will make our answer 2 and 9

Can you give me some insight in javascript ?

  • Can you elaborate more about what you exactly want? – Optimus Jul 15 '20 at 12:50
  • Please visit the [help], take the [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output using the `[<>]` snippet editor. – mplungjan Jul 15 '20 at 12:50
  • Take a look here: [How to find indices of all occurrences of one string in another in JavaScript?](https://stackoverflow.com/questions/3410464/how-to-find-indices-of-all-occurrences-of-one-string-in-another-in-javascript) – alexP Jul 15 '20 at 12:57
  • Sorry, i mean the expected will print output 2 and 9. – ryard firdaus2 Jul 15 '20 at 13:14

2 Answers2

1

do you mean something like this?

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

EDIT: make a function returning the indices

With the help of this answer:

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)
Jan Stránský
  • 1,671
  • 1
  • 11
  • 15
0

I'm not sure I understand the question.

Index could be found with indexOf and lastIndexOf.

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

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

More documentation could be found here, https://www.w3schools.com/jsref/jsref_lastindexof.asp

This help you?

Zeppi
  • 1,175
  • 6
  • 11