The code does not pass the first check

I have a function in which I first check that the string passed as an argument has only letters or not. But he always comes back as false. Below is my jsfiddle

function takeString (str) { var regex = "/^[A-Za-z]+$/"; if (str.match(regex)) { if (str.charCodeAt(0) === str.toUpperCase().charCodeAt(0)) { alert('true'); return true; } else { alert('false'); return false; } } else { alert('Only letters please.'); } } takeString('string'); 

The above code always warns Only letters please .

+7
source share
1 answer

You need to get rid of quotes to make regex regular expression literal:

 var regex = /^[A-Za-z]+$/; 

Here's the updated script .

Currently regex refers to a string literal. When you pass something that is not a regular expression object or a literal to String#match , it implicitly converts this argument to a regular expression object (see ES5 15.5.4.10 ):

  • If Type (regexp) is Object, and the value of the [[Class]] internal property of regexp is "RegExp" , then let rx be regexp;
  • Else, let rx be the new RegExp object, created as if the expression new RegExp( regexp ) , where RegExp is the standard built-in constructor with this name.

So your regex is interpreted like this (since the string contains the slash characters that you expected to delimit the regex literal):

 var regex = /\/^[A-Za-z]+$\//; 

It can't compare to anything, as it searches for a forward slash, followed by the beginning of a line.

+9
source

All Articles