Skip to content
Advertisement

Finding first index after symbol

I need to extract emails from random text strings. For example:

JavaScript

I found out how can i find end of email:

JavaScript

But how can i find it’s start index? Maybe we could reverse string and find first ‘ ‘ after @ but how can we do it?

Advertisement

Answer

This is a very non-trivial approach without using regular expression: you can reverse the string.

JavaScript

As a one-liner:

JavaScript

Note that the second find is looking for a space after the email address, which is the example you gave. You might ask what if the string ends with the email? That’s fine, since in that case find will return -1 which is the end of the string, thus you are still able to get the correct email address. The only exception is, there are other characters followed by the email address (i.e., a comma).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement