0

Can someone please explain this strange behavior in Javascript? When I do comparisons using the match() method I don't get the expected result.

var mat_1 = "wpawn";
var mat_2 = "wRook";

//compare both; do they have the same first letter? 

alert(mat_1.match(/^\w/) + " seems equal to " + mat_2.match(/^\w/));
if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
    alert("They are really equal")
}

//another approach

if (mat_1[0] === mat_2[0]) {
    alert("Yes! Equals")
} 
Some programmer
  • 301
  • 1
  • 12
Peristilo peris
  • 105
  • 1
  • 7

3 Answers3

1

match produces an array. You should really use an array comparison function, but for the sake of simple demonstration, try this - the first match value is selected and compared. All 3 alerts are triggered:

var mat_1 = "wpawn";
var mat_2 = "wRook";

//compare both; do they have the same first letter? 

alert(mat_1.match(/^\w/)+" seems equal to "+mat_2.match(/^\w/));
if(mat_1.match(/^\w/)[0] === mat_2.match(/^\w/)[0]){alert("They are really equal")}

//another approach

if(mat_1[0] === mat_2[0]){alert("Yes! Equals")}  
sideroxylon
  • 4,338
  • 1
  • 22
  • 40
1

Match returns an array of matches:

String.prototype.match(pattern: Regex): Array<string>

Your first evaluation will always fail as you are comparing two arrays.

This is the correct way for what you are trying to achieve.

'myWord'.match(/^\w/)[0] == 'mIsTeRy'.match(/^\w/)[0]

Although if you wanna truly use the regex to check the first letter, I wouldn't recommend it. Too much overhead for something too trivial (just my two cents).

Have fun coding! :)

Vlad Jerca
  • 2,194
  • 1
  • 10
  • 5
1

in the following lines of code you are checking the variables mat_1 and mat_2 for whether both the words starts with 'w', btw match() returns an array

if (mat_1.match(/^\w/) === mat_2.match(/^\w/)) {
    alert("They are really equal")
}

you can try something like

if (["w"] === ["w"]) {
    console.log("seems equal");
} else {
    console.log("not equal");
}

for array comparison you can check this post

what you have to do here is

if (["w"][0] === ["w"][0]) { // match for the elements in the array
    console.log("seems equal");
} else {
    console.log("not equal");
}
Community
  • 1
  • 1
Some programmer
  • 301
  • 1
  • 12