-2

I'm fairly new to regular expressions and I'm trying to compare two strings together using regex as a place holder/wildcard for certain values that can change in the string that I'm not concerned with. However, if I implement the following code:

var regex = /my .* is/;    

var str1 = "Hello, my name is... not important.";
var str2 = "Hello, " + regex + "... not important.";


var result = str1 === str2;

console.log(str1);
console.log(str2);
console.log(result);

I would expect the return to be:

"Hello, my name is... not important."
"Hello, my name is... not important."
true

Instead I get this:

"Hello, my name is... not important."
"Hello, /my .* is/... not important."
false

Can anyone enlighten me as to what's going on and how I might fix it?

JohnN
  • 968
  • 4
  • 13
  • 35
  • 1
    "*It looks like it's converting the regular expression to a string.*" that's *exactly* what happens. I'm not even sure what you want to happen instead. When you do `string + anything` you perform string concatenation and `anything` is coerced into a string. – VLAZ Apr 08 '20 at 18:42
  • @Taplar, you're right. It's a quirk with my IDE where it usually flags me a warning when throwing a non string into that function because it's supposed to use the string data type and I've just gotten into the habit of adding that to get rid of the warnings. It's actually `test.log` but I changed it to `console.log` to be more universal. – JohnN Apr 08 '20 at 18:45

2 Answers2

1

As you yourself noted, concatenating an object (in this case, a regex instance) to strings will coerce the object to string. This is expected behavior.

What you want instead is regex.test(string) (string.match(regex) would also work but is not as semantically accurate).

let regex1 = /my .* is/;
let regex2 = /^Hello, my .* is... not important\.$/;

let str = "Hello, my name is... not important.";

console.log(str);
console.log(regex1);
console.log(regex2);
console.log(regex1.test(str));
console.log(regex2.test(str));

regex1 will test for the phrase my _blank_ is, while regex2 will test for the exact statment mtaching Hello... important.

junvar
  • 11,151
  • 2
  • 30
  • 46
0

When concatenating any variable with a string in javascript, javascript will cast everything to a string and concatenate. For example,

var a = 5;
var str = "The value of a is " + a;
console.log(str)

would print "The value of a is 5"

This is causing the value of str2 to be "Hello, /my .* is/... not important."

Look at this answer for comparing two strings with wildcards.

Manav Bokinala
  • 177
  • 1
  • 2
  • 9