I'm using a regular expression to find all occurrences of a certain string in another string, while ignoring any whitespaces and different cases.
Below is my current code:
var str = word.substring(0,1)+"\\s*";
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*";
str = str + word.substring(word.length - 1,word.length);
var regEx = new RegExp(str, "gi");
An example would be if var word = "foobar"
:
var word = "foobar";
var str = word.substring(0,1)+"\\s*"; // declares the string as "f\\s*"
for (var i = 1; i < word.length - 1; i++) str = str + word.substring(i,i+1)+"\\s*"; // will add every character together with \\s* to 'str' like this: "f\\s*o\\s*o\\s*b\\s*a\\s*"
str = str + word.substring(word.length - 1,word.length); // will add the last character without \\s* like this: "f\\s*o\\s*o\\s*b\\s*a\\s*r"
var regEx = new RegExp(str, "gi"); // outputs /f\s*o\s*o\s*b\s*a\s*r/gi
This is working but it does not feel like the best way to solve it. I would be grateful if anyone had a prettier solution to this.