Reputation: 33408
How can i find a word that doesn't match with the searchcriteria, however has some equal letters in it?
Here's a fiddle to play a bit around.
If, the user types in au
The first 2nd entries are displayed. But how can I achieve that the same thing happens when the user types in ua
?
JS
I use the following to search for the value
from an input
and check if it exists in a list:
$("#search").on("keyup click", function () {
var value = this.value.toLowerCase();
$("#list").children().each(function () {
var text = this.innerText.toLowerCase();
$(this)[text.indexOf(value) !== 0 ? 'hide' : 'show']();
});
});
HTML
<input type="search" id="search">
<ul id="list">
<li><a href="#/australia/">Australia</a></li>
<li><a href="#/austria/">Austria</a></li>
<li><a href="#/belgium/">Belgium</a></li>
<li><a href="#/brazil/">Brazil</a></li>
<li><a href="#/canada/">Canada</a></li>
<li><a href="#/denmark/">Denmark</a></li>
<li><a href="#/finland/">Finland</a></li>
<li><a href="#/france/">France</a></li>
<li><a href="#/germany/">Germany</a></li>
...and so on...
</ul>
I'm not really familiar with RegExp
, but i think that this will do the trick may?!
Upvotes: 4
Views: 1003
Reputation: 272116
I just made up this function. It returns true if text
contains the sub-string value
; even if the letters are scrambled **:
function fuzzyContains(text, value) {
// for value = "THE", build the regex /[the]{3}/ and test
var valueCopy = value.toLowerCase().replace(/\W/g, "");
var regexp = new RegExp("[" + valueCopy + "]{" + valueCopy.length + "}");
return regexp.test(text.toLowerCase());
}
fuzzyContains("Netherlands", "Nethe") // true
fuzzyContains("Netherlands", "Neteh") // true
fuzzyContains("Netherlands", "Nethl") // false
Update
Here is a revised version of the function. It returns true if text
contains all characters from value
**:
function fuzzyContains_v2(text, value) {
var textCopy = text.toLowerCase();
var valueCopy = value.toLowerCase().split("");
console.log(textCopy, valueCopy);
var a = $.grep(valueCopy, function (value) {
return textCopy.indexOf(value) == -1;
});
return a.length == 0;
}
fuzzyContains("Netherlands", "Nethe") // true
fuzzyContains("Netherlands", "Neteh") // true
fuzzyContains("Netherlands", "Nethl") // true
fuzzyContains("Netherlands", "Netlands") // true
** I have not tested the behavior when value
contains repeated characters. However I am sure the results would still be acceptable.
Upvotes: 3
Reputation: 2653
This isn't possible with RegExp, however you can use the following function to meet your needs:
function looseCharacterMatch(a, b) {
a = a.split("");
b = b.substring(0,a.length);
var c = true;
for (var i = 0; i < a.length; i++) {
if (b.replace(a[i], "") == b) {
c = false;
}
b = b.replace(a[i], "");
}
return c;
}
Upvotes: 2
Reputation: 35950
Try this out:
var text = this.innerText.toLowerCase();
text = text.replace(/([a-z]*)([A-Z]*)/, '$2$1');
Upvotes: 0