Tip: the pattern "\d" (backslash and lowercase "d") matches a number, and "\D" (uppercase this time) matches any other character. Remember that backslashes must be escaped in strings.
var rgx = new RegExp( "\\d" ); // Create match pattern for a number
var str = "I'm 3 years old.";
if( rgx.test(str) )
alert( "That string contains a number!" );
else
alert( "No number found..." );
var rgx = new RegExp( "hELlO", "i" ); // mixed-case pattern
var str = "I said 'Hello, my name is Charles' to the other guy";
if( rgx.test(str) )
alert( "The word 'hello' appears in that string!" );
Without passing the "i" modifier to the constructor, that statement would not have been true!var zip = "AhZX77845ASL*$_"; // Zip code between letters and gibberish
var rgx = new RegExp( "\\D", "g" ); // Global: match all non-digits
var clean = zip.replace( rgx, "" ); // Replace all non-numbers with blank
alert( clean ); // returns '77845'
Without the global modifier "g", only the first non-number would have been replaced!var rgx = /\D/g; // Enclose the pattern between 2 forward slashes
var zip = "AhZX77845ASL*$_";
var clean = zip.replace( rgx, "" );
alert( clean );
Literal notation is shorter and more legible; modifiers are added right after the second slash.var rgx = /fox/gi; // Match every word 'fox' and ignore letter casing
var str = "The foxy fox jumps before dancing the Foxtrot";
alert( str.replace( rgx, "wolf" ) ); // Click to run ->
var zip = "AhZX77845ASL*$_";
// Direct replace pattern with literal notation:
alert( zip.replace( /\D/g, "" ) );