I am trying to put all the words that have the letter e in a separate array yet I can not figure out how to input a variable into the Regular Expression.
I have already tried plugging a variable into a metacharacter of regex.
var inputletter = "e"
startlist = ["jambee", "dangen", "oragna", "sabotta"];
filter1 = [];
var regex = new RegExp(startlist, "g");
for (var i = 0; i < startlist.length; i++) {
if(regex.test(regex, "regex") == true) {
filter1.push(startlist[i])
}
};
console.log(filter1);
You can use array filter function and also use includes
to check if the word contains the character
var inputletter = "e" startlist = ["jambee", "dangen", "oragna", "sabotta"]; function filter1(arr, char) { return arr.filter(function(item) { return item.includes(char) }) } console.log(filter1(startlist, inputletter));
you are using test wrong:
let regex = new RegExp("e");
...
if(regex.test(startlist[i])) {...
If you don't mind moving away from using a regex, you can use Javascript's array.prototype.filter() , string.prototype.toLowerCase() and the string.prototype.includes() methods to create an array where each element has at least one 'e'
let startlist = ["jambee", "dangen", "oragna", "sabotta"]; let result = startlist.filter((element) => element.toLowerCase().includes('e')); console.log(result);
If you want to keep your existing code you simply need to test the letter (the regex consisting of just that letter) against each element in the array ( startlist[i]
).
const startlist = ['jambee', 'dangen', 'oragna', 'sabotta']; const filter1 = []; const regex = /e/; for (var i = 0; i < startlist.length; i++) { const word = startlist[i]; if (regex.test(word)) filter1.push(word); }; console.log(filter1);
Alternatively you can use a slightly more functional method using the array filter
method, and the string includes
method
const startlist = ["jambee", "dangen", "oragna", "sabotta"]; const filtered = startlist.filter(word => { return word.includes('e'); }); console.log(filtered);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.