JavaScript - Find only the strings in array that contain specific letters
by jarosciak
HTML
<div id="result"></div>
JavaScript
var wordsFound = [];
var minLenght = 5;
var words = ["Volkswagen", "volley", "voltage", "volume", "volumes", "voluntarily", "voluntary", "volunteer", "volunteered", "volunteers", "Volvo", "vomit", "vomiting", "Von", "Vote", "voted", "voter", "voters", "votes", "voting", "voucher", "vouchers", "vow", "vowed", "Vowel", "vowels", "vows", "certain", "clarinet", "voyage", "VS", "vulgar", "vulnerability"];
if (typeof Array.prototype.reIndexOf === 'undefined') {
Array.prototype.reIndexOf = function (rx) {
for (var i in this) {
if (this[i].toString().match(rx)) {
return i;
}
}
return -1;
};
}
const regex = /[xclarinet]+/ig;
let m;
while ((m = regex.exec(words)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
m.forEach((match, groupIndex) => {
var word = `${match}`;
if (word.length>minLenght) {
wordsFound.push(word);
}
//console.log(`${match}`);
});
}
wordsFound.sort(function(a, b){
// ASC -> a.length - b.length
// DESC -> b.length - a.length
return b.length - a.length;
});
document.getElementById("result").innerHTML = wordsFound[0];