thednp
thednp

Reputation: 4479

Javascript: compare against regex or other way

I know I can do /z/i.test(str) and I can also compare with both str === z || tre === Z, just I was curious if there is a short line like this

if (str === /z/i) { do the dew }

The above line should not check if str contains z|Z but if it's equal to z|Z.

Thank you :)

Upvotes: 1

Views: 57

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

JavaScript does not have =~ operator (like in Perl, Ruby, etc.).

When you write str === /\n|z/i, you are comparing a string to a RegExp object, which does not make sense and will yield unexpected results.

The /z/i.test(str) returns true if str contains z or Z.

If you need to use a non-regex way to check the same condition, use

if (z.toLowerCase().indexOf("z") > -1)

If you need to check if the string is equal to either z or Z, you can use

if (z.toUpperCase() === "Z")

Sample demo:

z = "Zoe"; 
if (z.toLowerCase().indexOf("z") > -1) {
  document.body.innerHTML = "'Z' or 'z' is present in 'Zoe'.<br/>";
}
z = "z"; 
if (z.toUpperCase() === "Z") {
  document.body.innerHTML += "The string  is equal to 'z' or 'Z'";
}

Upvotes: 1

Related Questions