If you are looking to determine if a specific word is present within a string, you can utilize the indexOf
method. However, standard methods may not yield accurate results. For instance:
str = "carpet, bycicle, bus"
str2 = "car"
What you want car word is found not car in carpet
if(str.indexOf(str2) >= 0) {
// This condition remains true
}
// Alternatively
if(new RegExp(str2).test(str)) {
// This condition also remains true
}
To enhance the accuracy of regex matching, consider refining the pattern slightly:
str = "carpet, bycicle, bus"
str1 = "car, bycicle, bus"
stringCheck = "car"
// Expected result - false
if(new RegExp(`\b${stringCheck}\b`).test(str)) {
}
// Expected result - true
if(new RegExp(`\b${stringCheck}\b`,"g").test(str1)) {
}