john c. j.
john c. j.

Reputation: 1185

Regex inside `if` check

I'm trying to use regex inside if. Strange, but it doesn't work. How it may be fixed?

It works:

var lang = 'lang-js';
if (lang == 'lang-js') {
  alert('ok');
}

It works too (just for testing purposes):

var lang = 'lang-js';
if (lang == 'lang-' + 'js') {
  alert('ok');
}

But this one doesn't work:

var lang = 'lang-js';
if (lang == 'lang-' + /[a-z]/) {
  alert('not ok');
}

Upvotes: 0

Views: 184

Answers (2)

MypKOT-1992
MypKOT-1992

Reputation: 191

its because typeof /[a-z]/ == 'object' and where ''+/[a-z]/ working toString and your result will be string lang-/[a-z]/

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190941

use something like this

if (/^lang-[a-z]/.test(lang)) {

you might have to adjust the regex as this just looks for one char.

Upvotes: 5

Related Questions