Created
October 2, 2024 17:27
-
-
Save undfine/130e45b760b33a973b0aae770e5dbea3 to your computer and use it in GitHub Desktop.
Different ways of checking if an item from an array exists within a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Iterates over an array and returns true if any are found | |
| function itemInStr(str, arr) { | |
| return arr.some(item => str.includes(item)); | |
| } | |
| // uses Regex to test if a string is in the array, returns true if found | |
| function testItemInStr(str,arr){ | |
| let regex = new RegExp(arr.join("|"), "i"); | |
| return regex.test(str); | |
| } | |
| // Check if array contains the string (case insensitive) | |
| function arrayContainsStr(str, arr) { | |
| return arr.some(item => item.toLowerCase() === target.toLowerCase()); | |
| } | |
| const array = ['item1', 'item2', 'item3']; | |
| const longStr = "This is a string containing item2"; | |
| const shortStr = "item2"; | |
| // native (ES6) way to check if string is in Array (exact match) | |
| array.includes(shortStr); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment