Skip to content
Advertisement

Javascript regex matching at least one letter or number?

What would be the JavaScript regex to match a string with at least one letter or number? This should require at least one alphanumeric character (at least one letter OR at least one number).

Advertisement

Answer

In general, a pattern matching any string that contains an alphanumeric char is

.*[A-Za-z0-9].*
^.*[A-Za-z0-9].*
^[^A-Za-z0-9]*[A-Za-z0-9][wW]*

However, a regex requirement like this is usually set up with a look-ahead at the beginning of a pattern.

Here is one that meets your criteria:

^(?=.*[a-zA-Z0-9])

And then goes the rest of your regex. Say, and min 7 characters, then add: .{7,}$.

var re = /^(?=.*[a-zA-Z0-9]).{7,}$/; 
var str = '1234567';
 
if ((m = re.exec(str)) !== null) {
  document.getElementById("res").innerHTML = m[0];
}
<div id="res"/>
Advertisement