Depending on your strings in your array, using a regular expression (I know you said you were reluctant to use them as you feel you may go wrong, but I thought I'd show some examples) may be enough. Here we match on a word boundary \b
, followed by an o
:
const fruits =["apple orange", "Orange", "banana", "banana", "apple"]
const filterdFruits = fruits.filter(item => /\bo/i.test(item))
console.log(filterdFruits)
The word boundary is zero-length, and matches the following:
- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
The first and last options allow us to match both "Orange"
and "apple orange"
. Note that the word boundary matches between non-word characters, so apple $orange
would also be a valid match. We can change the regex a little to fix this case, where we only match words that start with o
(^o
) or (|
) have an o
following a whitespace character \so
that is not preceded by ((?<!)
) the beginning of the string ^
:
const fruits =["apple orange", "Orange", "banana", "banana", "apple"]
const filterdFruits = fruits.filter(item => /^o|(?<!^)\so/i.test(item))
console.log(filterdFruits)
In both expressions above, the /i
means do a case-insensitive match. To make the above expressions dynamic so that they use the character
, with can use the RegExp
constructor, eg:
const fruits = ["apple orange", "Orange", "banana", "banana", "apple"];
const character = "o";
const filterdFruits = fruits.filter(item => new RegExp(String.raw`\b${character}`, 'i').test(item))
console.log(filterdFruits)
If character
is user-supplied, you need to start worrying about escaping your character
string so that regex can't be inserted as a value. There aren't any native ways to escape a string so that it can be used in a regular expression, so at that point, you might consider using a different approach such as Terry's