Jump to content

Regular Expressions


porzant

Recommended Posts

This will get you closer..var str = ...if (/[0-9]+/.exec(str)) {}However, the problem with JS regular expressions is they're not greedy. The above will match a part of the string..so if your string is "b2", it will return ["2"]. What you may want is something like:if (/[0-9]+/.exec(str) != null && /[0-9]+/.exec(str)[0].length == str.length) {}

Link to comment
Share on other sites

What I mean is somewhere on this site there's an example, where you can't post numbers because it's got /d/ somewhere.I want to put [0-9] in that place so it's only numbers, but I'm not sure where it goes, does it go in the value attribute?

Link to comment
Share on other sites

This expression will match only numbers - /^[0-9]+$/ - if there is a match, then the variable only contains numbers.Or, you could do the opposite and look for anything but numbers - /[^0-9]/ - if there is a match then there is a non-numeric character in the string.

var test1 = "556502";var test2 = "55g5O2";var reg = /^[0-9]+$/;if(test1.match(reg)){	alert(test1 + " is a number.");}if(test2.match(reg)){	alert(test2 + " is a number.");}

Also, keep in mind that javascript has a built in number checker: isNaN();

var test1 = "556502";var test2 = "55g5O2";if(isNaN(test1)){	alert(test1 + " is not a number.");}if(isNaN(test2)){	alert(test2 + " is not a number.");}

Link to comment
Share on other sites

You can adapt that code like so:

<html><body><script>function noLetters(e){	// Get the event object for IE, Firefox, Opera, etc.	e = (e) ? e : window.event;	// Get the code for which key was pressed (IE, Firefox, Opera, etc.)	var char = (e.which) ? e.which : e.keyCode;	// Get the actual letter from the character code.	var key = String.fromCharCode(char);	// Return false if isNaN is true, else return true if isNaN is false.	// Returning false from an event handler prevents the event (i.e.	// the keydown) from happening.	return !isNaN(key);}</script><input type="text" onkeydown="return noLetters(event);" /></body></html>

Link to comment
Share on other sites

Archived

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

×
×
  • Create New...