Jump to content

checking if string contains upper and lower case characters


Destramic

Recommended Posts

Do you want it to match for only numbers, upper-case and lower-case letters, or make sure the string contains at least one of each? Or even a string that only consists of numbers, upper-case and lower-case letters, and has to have one of each?

I'll leave the naming of it to you...

 

function nameHere(str) {
    return str.match(/[a-z]/) && str.match(/[A-Z]/);
}

 

This would be more apropriately added as a method to the String object by the way. That way instead of passing it as a parameter to the stand-alone function, you could simply call it like myString.nameHere() - which would be done with the following code:

 

String.prototype.nameHere = function() {
    return this.match(/[a-z]/) && this.match(/[A-Z]/);
}

 

But which you use it up to you of course.

thank you...although i could get it to work this way

 

	String.prototype.string_has_numbers = function(string)
{
	var regex = /\d/g;
	return regex.test(string);
}

var password_value = "test1";
password_value.string_has_numbers()

When you extend the object you don't pass the string in as a parameter, it's already available as this:

 

	String.prototype.string_has_numbers = function()
{
	return this.match(/\d/);
}

 

You don't need the 'g' modifier in that expression by the way. I'd consider renaming that method too, to be more in-line with the other String methods, like .indexOf(), .charAt(), etc.

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.