I have a function in which I am first checking that a string passed as argument has letters only or not. But it always return 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 alerts Only letters please.
You need to get rid of the quotes to make
regexa regular expression literal:Here’s an updated fiddle.
Currently,
regexrefers to a string literal. When you pass something that’s not a regular expression object or literal toString#match, it implicitly converts that argument to a regular expression object (see ES5 15.5.4.10):Your regular expression is therefore interpreted like this (since the string contains the forward slash characters you were expecting to delimit a regular expression literal):
That can’t match anything, since it’s looking for a forward slash, followed by the start of the string.