How to match the two strings with and without including spaces

You can compare so:

let val1 = 'cell phones';
let val2 = 'cellphones';

console.log(val1.replace(/\s/g, '') === val2.replace(/\s/g, '')) // true
//OR
console.log(val1.split(' ').join('') === val2.split(' ').join('')) // true

If you need some aggregation trick then you can try this

db.collection.aggregate([
  { "$project": {
    "name": {
      "$reduce": {
        "input": { "$split": ["$name", " "] },
        "initialValue": "",
        "in": { "$concat": ["$$value", "$$this"] }
      }
    }
  }},
  { "$match": { "name": "cellphones" }}
])

You can test it Here


You can first start by stripping out the spaces on both the strings before comparing them, for example:

let a = "cell phone";
let b = "cellphone";
let c = "cell phones"

const stripSpaces = s => s.replace(/\s/g, '');

// compare
console.log(stripSpaces(a) == stripSpaces(b)); // true
console.log(stripSpaces(a) == stripSpaces(c)); // false