0

I have the generic fuzzy search right now, so that if type "a" it'll return me every word that contains an A. However I want a more refined search that does this.

For example I have the word: 'Frankster Muniz'

searching "frank","fr","f", "mun", "m" will indeed return 'Frankster Muniz'

searching "rank","ster","r", "niz" will not return anything

it must match the first beginning words,I have no idea where to start here. I am very new to regex. Thank you

EEE
  • 149
  • 1
  • 7
  • 1
    What is about your try? Post your regex-expression to look, what's running wrong. – Y4roc Jun 09 '17 at 14:23
  • 2
    something like `/\bfrank/i` ? aka: `RegExp("\\b" + term, "i")` passes your tests – dandavis Jun 09 '17 at 14:25
  • If you want to match a complete word, use `RegExp(\`\\b${search}\\w*\`, 'i')` - don't forget to [escape](https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript) `'search'`. – le_m Jun 09 '17 at 14:28

2 Answers2

0

You could begin with this:

If input is user-input and name is name on database ,

var name = "Frankster Muniz";
var input = "Frank";

function match(name,input){
var matched = 0;
if(name.match(new RegExp("\\b"+input+".*","i")))
  matched=1;
return matched;
}

console.log(match(name,"Frank"));
console.log(match(name,"ster"));
Mrigank
  • 136
  • 1
  • 8
0

You can start matching at the beginning of words by using the word boundary character \b. So the power of the regex becomes:

new RegExp(`\\b${input}`, 'i');

Check out the interactive example:

let names = [
  'Frankster Muniz',
  'Sarah Walin',
  'Tyler Robinson',
  'Ronald Muniz'
];

let results = document.querySelector('#results');
let input = document.querySelector('input');
input.addEventListener('input', function() {
  findUsers(this.value);
});

buildList(names);

function findUsers(input) {
  let reg = new RegExp(`\\b${input}`, 'i');
  let found = names.filter(name => reg.test(name));
  buildList(found);
}

function buildList(names) {
  let html = '';
  names.forEach(name => html += `<li>${name}</li>`);
  results.innerHTML = html;
}
<label>Filter:</label>
<input id="search">
<br><br>
<div>Names:</div>
<ul id="results"></ul>
KevBot
  • 17,900
  • 5
  • 50
  • 68