How can I make a partial string match in Javascript?
e.g. to match 'Alf'
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>
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With