Matching the first occurrence of each letter in string


What I’d like to do is match the first occurrence of two or more letters, so for example, I’d like to highlight A and F from the string below:


But only the first A and only the first F

I’ve tried:


But no joy…

Any ideas appreciated…


What is the purpose? Also, why can’t you use something simple, like .indexOf()
I agree on the indexOf. If you have no other way, you can give a try to ^[^A]*(A) when searching for first occurence of A (as there is no variable length lookbehind using javascript RegExp). Capturing group will let you know the occurence position in the string.
Unless you want to do something with the position of A and F in the string, simply includes or indexOf will do.



This should give you the match you want:

  • ^ asserts position at start of the string
  • .*? matches any character (except for line terminators)
  • *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)


Only when F is always is behind A, which almost certainly is not the case.
That doesn’t seem to work: – it matches everything from A to F – but I just need A and F
2 hours ago
Another example… I would like to highlight (wrap around some span tags) the words shark and trip. But only the first instance of each word:
2 hours ago
I am on a shark fishing trip, a fishing trip for shark I am on.
2 hours ago
so words 5 and 7 would be highlighted if you see what I mean?
2 hours ago