I have found the below Javascript recently, and (believe) I understand its operation, but cannot figure out (what appears) to be a ¿regex string class? (“/\W/.test”)
function AlphaNumericStringCheck(text)
{
if (/\W/.test(text.replace(/^\s+|\s+$/g,""))) return false;
return true;
}
Can someone put a name to this technique, so I can research it more?
The
/\W/in your source code is a regular expression literal (MDC link, as MDC is about 18X clearer than the specification). Just as with a string literal (“foo”), a regular expression literal is a way of writing regular expressions in the code. The/characters in a regular expression literal are analogous to the quote characters in a string literal. In a string literal, what’s inside the quotes is the content of the string; in a regular expression literal, what’s inside the/characters is the regular expression. (There can also be flags following the ending/.)So this:
…creates a regular expression object for the regular expression
\W(match one word character). It’s (essentially) equivalent to:Note that in the long form, I had to escape the backslash in the string, since backslashes are special in string literals. This is one of the reasons we have regular expression literals: Because it gets very confusing, very quickly, when you have to escape all of your backslashes (backslashes being a significant part of many regular expressions).
Regular expressions are objects, which have properties with functions attached to them (effectively, methods, although JavaScript doesn’t technically have methods per se). So
/\W/.test(...)calls thetestfunction on the regular expression object defined by the literal/\W/.