简体   繁体   中英

Comparing two strings with Regular Expressions in JavaScript

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM