jasonc Posted December 17, 2011 Share Posted December 17, 2011 I have used many versions of code to validate an email in JS but after using it, it fails when another email format shows it face that the code thinks is wrong; but in fact is a valid email. So opted to using this method which would server the purpose I am after but do not know how to search for the seed from the end of the string instead of from the start. here is the code I am wanting to use but not sure how I search for the '.' starting from the end of the string. function checkEmailValid2(email) { s = email.indexOf(' ') + 1; // is there a space e = email.indexOf('@') + 1; // find the @ f = email.indexOf('.') + 1; // find the . if ( email != '' && s == 0 && e && f > e + 1 && f < email.length) { return true; } else { return false; } } Quote Link to comment https://forums.phpfreaks.com/topic/253391-how-to-search-from-end-of-string-in-js/ Share on other sites More sharing options...
sunfighter Posted December 18, 2011 Share Posted December 18, 2011 lastIndexOf() in js will tell you the last occurrence position of a character or word in a string. <script language=javascript> var emstring = "PUT YOUR EMAIL STRING HERE"; var result = emstring .lastIndexOf("."); document.write(emstring .length+'<br />'); // This is not needed document.write(result+'<br />'); // this tells you where it's at!!!! </script> The only gotcha with this is it starts counting from zero, so the very first character will return 0. Quote Link to comment https://forums.phpfreaks.com/topic/253391-how-to-search-from-end-of-string-in-js/#findComment-1298940 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.