This is a function that i have created to search for a pattern
function abc(x)
{
for(var i=0;i<x.length;i++)
{
if("%/-+".indexOf(x[i])>=0)
{
return i;
}
}
return -1;
}
I tried to make this function better using regex as follows but it didnt seem to work properly as follows
str.search(/[%/-+/]/);
can someone tell me what my mistake is here
Search finds an index, so you need to check if the index is not -1:
str.search(/[%*-+/]/) !== -1
But you want just true/false, so use the Regexp method test
instead:
/[%*-+/]/.test(str)
actually i need the index too, for some reason the code shows “0-0”.search(/[%-+/]/); gives -1 as result and “0-0”.search(/[%-/+]/); gives 1 as reult,can you help on why that happens
I don’t understand, those are the same: the index of “-” is 1, so it returns 1.
i tried it out on the console and got those results, thats why i asked
try putting the -
near the square bracket otherwise it may be interpreted as a “from this character to this character” like in [a-z]
, if you want just, a, z and dash you would need to write [az-]
thanks, I think the problem must be with what you mentioned
what are you using that I get this?
Huh, that’s weird. It’s Node on Android, v6.11.4 ARM