Skip to content

Regex test method returning more than a specific string [closed]

I’m trying to search a specific string like 9.7 in an array using regex test method, but, it’s returning values that contains 1984, 1987 in the same row and also 9.7 rows.

searchText= '9.7';
items = [ {description: "MERCEDES BENZ L 1519 - OM 355/5 9.7 L 10V SOHV L5 1973 1987"}, {description: "MERCEDES BENZ LB 2219 - OM 355/5 9.7 L 10V SOHV L5 1973 1980"}, {description: "MERCEDES BENZ LS 1932 - OM 355/6 LA 11.6 L 12V SOHV L6 1984 1987"}, {description: "MERCEDES BENZ O 370 RSD OM 355/5 11.6 L 10V SOHV L5 1985 1987"} ] 

let returnArray = [],
      splitText = searchText.toLowerCase().split(/s+/),
      regexp_and = '(?=.*' + splitText.join(')(?=.*') + ')',
      re = new RegExp(regexp_and, 'i');

    for (let x = 0; x < items.length; x++) {
      if (re.test(items[x][field])) {
        returnArray.push(items[x]);
      }
    }
    return returnArray;

Expected output:

array = [ {description: "MERCEDES BENZ L 1519 - OM 355/5 9.7 L 10V SOHV L5 1973 1987"}, {description: "MERCEDES BENZ LB 2219 - OM 355/5 9.7 L 10V SOHV L5 1973 1980"}]

Could anyone help me? Thanks.

Answer

The . is a special char meaning any character. So when your search string contains it you need to escape it or it will be treated like the wildcard.

use

const splitText = searchText
   .toLowerCase()
   .split(/s+/)
   .map(token=>token.replace(/./g,'\.'));

but keep in mind that this might happen with other special characters

const searchText = '9.7';
const items = [{
  description: "MERCEDES BENZ L 1519 - OM 355/5 9.7 L 10V SOHV L5 1973 1987"
}, {
  description: "MERCEDES BENZ LB 2219 - OM 355/5 9.7 L 10V SOHV L5 1973 1980"
}, {
  description: "MERCEDES BENZ LS 1932 - OM 355/6 LA 11.6 L 12V SOHV L6 1984 1987"
}, {
  description: "MERCEDES BENZ O 370 RSD OM 355/5 11.6 L 10V SOHV L5 1985 1987"
}];

const returnArray = [];
const splitText = searchText
  .toLowerCase()
  .split(/s+/)
  .map(token => token.replace(/./g, '\.'));
const regexp_and = '(?=.*' + splitText.join(')(?=.*') + ')';
const re = new RegExp(regexp_and, 'i');
const field = 'description';

for (let x = 0; x < items.length; x++) {
  if (re.test(items[x][field])) {
    returnArray.push(items[x]);
  }
}

console.log(returnArray);