I need to have the best requirement for matching two dynamic strings fetched from API.
Currently, I have two different objects that return strings dynamically. I need to perform a certain action if the strings are matched. The strings cases differ in some cases, they do not match completely.
To perform the equality (say partial one), I tried to utilize the power of regular expressions. But it doesn't seem to work for me.
const secondaryStringValue = 'accupuncture';
const mainStringValue = 'Accupuncture';
const matchBothStrings = `/${secondaryStringValue}/i`;
if (mainStringValue.match(matchBothStrings)) {
alert('matched');
} else {
alert('unmatched');
}
The values in both the variables secondaryStringValue & mainStringValue are obtained dynamically from the API from an array/object. For example purpose, I've extracted one of those values as a static string in variables.
But this solution doesn't seem to work. It always returns the output as 'unmatched
' even when one of the results should match.
If I compare the strings statically like this:
const mainStringValue = 'Acupuncture';
if (mainStringValue.match(/acupuncture/i)) {
alert('matched');
}
else {
alert('unmatched');
}
this works, but I cannot use this since this is just a static comparison, not a dynamic one.
If anyone can help to resolve the same bit soon, it is highly appreciated.
Thanks in advance
CodePudding user response:
Move it into new RegExp(dynamicVariable, 'i')
const mainStringValue = 'Acupuncture';
var dynamicVariable = 'acupuncture';
var regex = new RegExp(dynamicVariable, 'i');
if (mainStringValue.match(regex)) {
alert('matched');
}
else {
alert('unmatched');
}