Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match the two strings with and without including spaces

For example: In DB I've the string value like "cell phones". If I get the string value like "cellphones" from frontend. How can I compare it with DB string and get the related string values in response.

like image 367
Allu Manikyam Avatar asked Aug 30 '18 07:08

Allu Manikyam


People also ask

What is the correct way of comparing 2 strings with each other?

Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

What are the 3 ways to compare two string objects?

In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.

How do you check a string with spaces?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do you check if string is empty with spaces?

In C#, IsNullOrWhiteSpace() is a string method. It is used to check whether the specified string is null or contains only white-space characters. A string will be null if it has not been assigned a value or has explicitly been assigned a value of null.


7 Answers

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
like image 52
Denis Kuratovich Avatar answered Oct 16 '22 20:10

Denis Kuratovich


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

like image 43
Ashh Avatar answered Oct 16 '22 20:10

Ashh


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
like image 42
ProfNandaa Avatar answered Oct 16 '22 21:10

ProfNandaa


Just remove those spaces from the response you are getting after query find then pass the response to require input field. Then match that string with front-end or input string. If both matches load the required content. Suppose the collection name is Category. Then the sample query will be like this

Category.find().exec((err, categories) => {
         var details=[]
         var matchCategory=[]
         categories.map((category,key)=>{
           var obj ={}
           obj.name = category.name.toLowerCase().replace(/\s/g, "")
           details.push(obj);
         })
       if(details.length > 0){
         var detailsLength=details.length
         details.map((category,key)=>{
             if(category.name=="cellphones"){ // match your input string 
               matchCategory.push(category)
             }
             detailsLength--
         })
         if(detailsLength==0){
               resolve(matchCategory);
         }
       }
     })

This may help you to reach out.

like image 36
Tripura Avatar answered Oct 16 '22 21:10

Tripura


Answers below this question are good, like using where and Regex, but might be at their best if you got a small number of docs that you may want to query from.

If you got many docs, I'd suggest you: 1. Use an extra field like cellphone without any space, if the values of the original field are expected to be short. 2. Try using search engines, like ElasticSearch, or MongoDB's own text search, to find what you need, not only cell phone to cellphone, but mobile phone even smartphone. Actually, when you google something, the suggestions while you're typing are also coming from similar but more complex algorithms.

like image 40
YLS Avatar answered Oct 16 '22 21:10

YLS


Given a document like this:

{
    "text" : "cell phones"
}

You could use the $where operator like this:

db.collection.find({
    $where: function() {
        return this.text.replace(' ', '') == "cellphones"
    }
});

I wouldn't necessarily recommend this for big collections (performance might not be great). However, even with big collections you could supposedly achieve some pretty ok performance by adding an extra filter on the "text" field to filter out all documents that don't start with the correct first character(s):

db.collection.find({
    "text": { $regex: "^" + "cellphones".charAt(0) }, // this will use an index on the "text" field if available
    $where: function() {
        return this.text.replace(' ', '') == "cellphones"
    }
});

Or perhaps even this version with yet another filter in the $where bit that checks the string lengths for a reduced number of string comparisons:

db.collection.find({
    "text": { $regex: "^" + "cellphones".charAt(0) }, // this will use an index on the "text" field if available
    $where: function() {
        return this.text.length >= "cellphones".length // performance shortcut
               && this.text.replace(' ', '') == "cellphones"
    }
});
like image 25
dnickless Avatar answered Oct 16 '22 22:10

dnickless


try replacing empty string from query string first, and then compare to the field as

db.test.find(function() { 
    return this.data(function(elm) {
        "cell phones".replace(/ /g,"") == elm.name
    });
});
like image 33
MohammadReza Alagheband Avatar answered Oct 16 '22 20:10

MohammadReza Alagheband