FaheemAhmadGul
asked on
Javascript function to filter a an array of strings based on starting letters of the strings in the array
I need help writing a Javascript function which will take a string as an arugment and then filter out an array of strings starting with the string I pass as an argument.
So if I have the following array:
let words = ['simple', 'single', 'side', 'sacked', 'apple', 'orange']
I need a javascript funtion that will look at every string in this array, and give me a second array called myFilteredWords which start with the letters 'si" - assumuming that I pass 'si" as an argument to the funtion.
So if I have the following array:
let words = ['simple', 'single', 'side', 'sacked', 'apple', 'orange']
I need a javascript funtion that will look at every string in this array, and give me a second array called myFilteredWords which start with the letters 'si" - assumuming that I pass 'si" as an argument to the funtion.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Give this a try:
var words = ['simple', 'single', 'side', 'sacked', 'apple', 'orange'];
const regex = new RegExp('^si', 'g')
const myFilteredWords = words.filter(value => regex.test(value));
console.log(myFilteredWords);
startsWith() does not appear to be supported on IE
Julian
I think you are right, it's not supported in IE11 anyway - not sure about other versions.
I think you are right, it's not supported in IE11 anyway - not sure about other versions.
ASKER
Many thanks all the experts for your comments. As both Julian's and Norie's solutions were most helpful and I accepting both. Hope this is OK.
You are welcome.
Open in new window