Jump to content

how to search from end of string in JS


jasonc

Recommended Posts

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;
	}
}

Link to comment
https://forums.phpfreaks.com/topic/253391-how-to-search-from-end-of-string-in-js/
Share on other sites

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.