filter all words in an array that have a capital letter in javascript

One way to filter all words in an array that have a capital letter in JavaScript is by using the filter() method in combination with a regular expression.

index.tsx
const words = ["apple", "Banana", "Cherry", "date", "eggplant"];

const capitalizedWords = words.filter(word => /[A-Z]/.test(word));

console.log(capitalizedWords); // Output: ["Banana", "Cherry"]
197 chars
6 lines

In this example, we first define an array of words. We then use the filter() method on this array and pass in a callback function that takes in each word element in the array as an argument.

Within the callback function, we use a regular expression /[A-Z]/ to test if the word contains any uppercase letters. If the word contains at least one uppercase letter, the test() method returns true and the word is included in the resulting capitalizedWords array. Otherwise, the word is filtered out of the array.

Note that this regular expression only matches uppercase letters in the range A-Z. If you want to match accented uppercase letters or uppercase letters in other character sets, you may need to modify the regular expression accordingly.

gistlibby LogSnag