Reputation: 8086
I'm learning javascript and this just doesn't make sense to me. test()
returns true or false if a character is a match. So can someone please explain why my code below is not working?
var str = "hello*3";
var arr = str.split('');
for(var i in arr){
re = new RegExp("/[a-z]/i");
if(re.test(arr[i])) {
console.log(String.fromCharCode(arr[i].charCodeAt() + 1));
}
}
re.test(arr[0]); //arr[0] == 'h'
// false
Updated example:
var re = new RegExp("/[a-z]/i");
re.test('h');
// returns 'false' (I'm expecting this to be true)
Upvotes: 2
Views: 478
Reputation: 70722
If you want to create a RegExp Object you must supply the correct syntax.
Syntax:
var re = new RegExp(pattern, modifiers);
var re = /pattern/modifiers;
So you could use either of the following here.
var re = new RegExp('[a-z]', 'i');
var re = /[a-z]/i;
Upvotes: 2
Reputation: 8855
You don't need the /
when using the RegExp
and you pass flags as the second param
This should work re = new RegExp("[a-z]", "i");
or the literal form
re = /[a-z]/i;
More info can be found on MDN here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Some info from the link above
Constructor Literal and constructor notations are possible:
/pattern/flags;
new RegExp(pattern [, flags]);
pattern
The text of the regular expression.
flags
If specified, flags can have any combination of the following values:
g
global match
i
ignore case
m
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
y
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes). This allows the match-only-at-start capabilities of the character "^" to effectively be used at any location in a string by changing the value of the lastIndex property.
Upvotes: 5