Forum Moderators: open
I want to only allow integers that start from 1, with no minus or anything like that. Just 1, 2, 3, 100000 etc etc.
I have the following regex:
foo = foo.replace(/[^1-9]/, '');
However this doesn't quite work in the way I want. As if I write 20 it will convert it to 2.
Can anyone point my in right direction?
Thanks
I want to only allow integers that start from 1, with no minus or anything like that. Just 1, 2, 3, 100000 etc etc.
This ^, when the first character in a class, is a not operator, meaning any character NOT . . . . so replace(/[^1-9]/, ''); means any character NOT 1-9. So if you have
102
It will turn it to
12
You want to use ^ as "starts with." So try
foo = foo.replace(/^[0]\d*/, '');
or
foo = foo.replace(/^[^1-9]\d*/, '');
In this context, the first ^ means "starts with" a single digit that is zero (as, any other number is fine, right? same thing as the second example, not 1-9), followed by zero or more of ANY digit. If this pattern is found, replace with a blank string. Is that what you meant?
Edit: Got me curious, demonstration by example rules. :-) Run it, then remove the first zero. Works with the [0] example above as well.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- doctype on one line -->
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Untitled</title>
<script type="text/javascript">
function noZero(foo) {
foo = foo.replace(/^[^1-9]\d*/, '');
alert('foo is ' + foo +'.');
return false;
}
</script>
</head>
<body>
<form action="" onSubmit="return noZero(document.getElementById('z').value);">
<input type="text" name="z" id="z" value="0120394">
<input type="submit" value="Test It">
</body>
</html>