I have a scenario where i want to compare the vehicle number from the database. If the number enterd is KA03ME0101 I will pick up only the number that is 3rd 4th and 7th till last elements from the string and compare it in database where I want to apply regex to do the same thing to number and compare it. Right now i am storing it as String.
vehicle_number : {
type : String
},
And this query does it for me for now
bookingSchema.statics.findBookingByVehicleNo = function(params, callback){
return this.findOne({
'$and' : [
{ 'booking_status' : { '$eq' : 'checked_in' }},
{ 'vehicle_number' : params.vehicle_number }
]
}).exec(callback);
}
Suppose the vehicle no is `KA03ME0101 , I want to write a query, where I can compare only the numbers that is excluding KA and ME and picking up only the numbers that is 030101. So the first two words are skipped and then pick up the 3rd and 4th number and then skip 5th and 6th and pick up the remaining number. From the user side I will pick up the number in the same way and then compare it. How can i apply regex to do this any lead would be helpful thankyou.
You can play around with regular expressions here: http://regexr.com/
For your case, you want to only look at digits, so simply remove non-digits and compare should do the trick:
var plates = [
'KA03ME0101',
'AK03EM0101'
];
var regularExpression = /\D/ig;
for (var indexA = 0; indexA < plates.length; indexA++) {
var a = plates[indexA];
for (var indexB = indexA + 1; indexB < plates.length; indexB++) {
var b = plates[indexB];
if (a.replace(regularExpression, '') == b.replace(regularExpression, '')) {
console.log(a, 'matches', b);
}
}
}
You can simply extract the numbers from the parameter and query using it.
So in your example params.vehicle_number.match(/\d+/g).join('') will give you 030101. So your query should be as follows:
'$and' : [
{ 'booking_status' : { '$eq' : 'checked_in' }},
{ 'vehicle_number' :params.vehicle_number.match(/\d+/g).join('') }
]