0

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');
}
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
john c. j.
  • 725
  • 5
  • 28
  • 81
  • Type `'lang-' + /[a-z]/` in the browser console and see what happens. You're not doing a regular expression test, you are concatenating a regex with a string, which produces a string, and then comparing that with another string. This has nothing to do with jQuery so I've removed that tag. – nnnnnn Mar 01 '17 at 01:54
  • http://stackoverflow.com/questions/6603015/check-whether-a-string-matches-a-regex – buræquete Mar 01 '17 at 01:55

2 Answers2

5

use something like this

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

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

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

MypKOT-1992
  • 191
  • 3