1

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.

tjespe
  • 704
  • 7
  • 17
  • 1
    Could you make an example, to understand it easier? – John Apr 08 '16 at 20:27
  • please show us input and expected output as your code is tough to understand in itself – Unamata Sanatarai Apr 08 '16 at 20:34
  • You can visit http://stackoverflow.com/questions/24395542/regex-ignore-case to ignore case. You also seem to be using the \s meta, so that takes care of all sorts of white space. – Jeff.Clark Apr 08 '16 at 20:34
  • Instead of making a regexp which includes the white space, consider removing the white space from the target string, and then just finding the desired string within that. –  Apr 08 '16 at 20:35
  • If you are looking to have already working code improved on, visit SE.CodeReview – Jeff.Clark Apr 08 '16 at 20:35
  • I updated the question now with an example. I cannot change the target string, considering it is a variable generated by the user. I didn't know there was a forum for code review, my question should probably have been posted there. – tjespe Apr 08 '16 at 20:40
  • Maybe you could try a [fuzzy search algorithm](http://stackoverflow.com/questions/9206013/javascript-fuzzy-search)? – Mottie Apr 08 '16 at 20:47

1 Answers1

3

You can use split and join to simplify this:

var word = "foobar";
var regex = new RegExp(word.split('').join('\\s*'), 'gi');
//=> /f\s*o\s*o\s*b\s*a\s*r/gi
anubhava
  • 761,203
  • 64
  • 569
  • 643