Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript matching strings to partial matches

Tags:

javascript

How can I make a partial string match in Javascript?

e.g. to match 'Alf'

  • 'Alfred' -> true
  • 'Alf' -> true
  • 'alf' -> true
  • 'al' -> true
  • 'altered' -> false
  • 'half' -> false
  • '' -> false
  • 'bob' -> false

https://jsfiddle.net/zbzc5tqe/1/

I would welcome shorter / more use of javascript inbuilt functions.

var arr = ['Alfred', 'Alf', 'alf', 'al', 'altered', 'half', '', 'bob'];

arr.forEach(function(element) {
  add(element + "->" + matches(element, 'Alf'));
});

function ignoreCase(s1, s2) {
  var needleRegExp = new RegExp('^' + s2 + "$", "i");
  return needleRegExp.test(s1)
}

function partializer(string) {
  var out = [];
  for (var i = 1; i < string.length; i++) {
    out.push(string.slice(0, i));
  }
  return out;
}

function matches(text, partial) {
  var parts = partializer(partial);
  for (var i = 0; i < parts.length; i++) {
    if (startsWith(text, parts[i])) {
      return true;
    }
  }
  return false;
}

function startsWith(text, element) {
  var s2 = text.split(0, element.length - 1);
  return ignoreCase(element, s2);
}

function add(text) {
  var olList = document.getElementById('list');
  var newListItem = document.createElement('li');
  newListItem.innerText = text;
  olList.appendChild(newListItem);
}
<ol id="list">
</ol>
like image 336
Ryan Leach Avatar asked Jun 13 '26 10:06

Ryan Leach


2 Answers

Seems like you just want to know if a string starts with the substring:

function test(arr, sub) {
  sub = sub.toLowerCase();
  return arr.map(str => str
    .toLowerCase()
    .startsWith(sub.slice(0, Math.max(str.length - 1, 1)))
  );
}

var arr = ['Alfred', 'Alf', 'alf', 'al', 'altered', 'half', '', 'bob'];

var results = test(arr, 'alf');
console.log(results);
like image 125
KevBot Avatar answered Jun 16 '26 18:06

KevBot


Using .indexOf to find if there is any matches in the string. Refer to

function matches(text, partial) {
  return text.toLowerCase().indexOf(partial.toLowerCase()) > -1;
}

function matchesCase(text, partial) {
  return text.indexOf(partial) > -1;
}

https://jsfiddle.net/zbzc5tqe/3/

Use the matchesCase() function if you would like to match case sensitive only.

like image 23
Chris Avatar answered Jun 16 '26 17:06

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!