Reputation: 3589
I'm trying to check for a value that matches in an array of strings.
So something like this works
const usernames = ['owlman', 'neo', 'trinity'];
const name = 'neo'
if(usernames.indexOf(name) > -1 ){
console.log('you found me')
}
else{
console.log('no luck finding user')
}
but what happens if you have a textarea comment, and you want to mention a user with comment data so you do something like this
const usernames = ['owlman', 'neo', 'trinity'];
const name = '@neo you look like the one!'
if(usernames.indexOf(name) > -1 ){
console.log('you found me')
}
else{
console.log('no luck finding user') // this gets callee
}
demo
https://jsbin.com/gepiqopiri/edit?js,console
How can i search for a specific value that is an array when there is corresponding data along with it . Is indexOf
the approach i want to be using ?
Upvotes: 0
Views: 33
Reputation: 1739
Check if name
includes any user from usernames
as below
const usernames = ['owlman', 'neo', 'trinity'];
const name = '@neo you look like the one!';
if(usernames.some(user => name.includes(user))) {
console.log('you found me'); // this will be called on match
} else {
console.log('no luck finding user');
}
Upvotes: 1
Reputation: 5118
indexOf
will only find a match for the exact object you pass to it. Your first example works because "neo" does exist as an item in the usernames
array. Your second example fails, however, because the array does not contain an entry for "@neo you look like the one".
You'll need to parse your name
string and extract a username, then use usernames.indexOf
to see if it exists. You can split the name
string at spaces and then check for a word that begins with '@', or you can use regex.
Splitting
var usernames = ['neo', 'other'];
var name = '@neo you look like the one';
// Split the name string at each space
var splitBySpace = name.split(' ');
// Get each item in the split where it begins with @
// The .map uses substring(1) to remove the @ prefix
var atNames = splitBySpace.filter(n => n.indexOf('@') === 0).map(n => n.substring(1));
console.log(atNames[0]); // neo
console.log(usernames.indexOf(atNames[0]) >= 0); // true
Regular Expressions
var usernames = ['neo', 'other'];
var name = '@neo you look like the one @other';
// Get each mentioned name with regex
var atNames = [...name.matchAll(/\@[^\s]+/g)];
// Strip @ prefix from each match
var atNamesToMatch = atNames.map(n => n[0].substring(1));
console.log(atNamesToMatch.length); // 2 ("neo" and "other")
console.log(usernames.indexOf(atNamesToMatch[0]) >= 0); // true
console.log(usernames.indexOf(atNamesToMatch[1]) >= 0); // true
Upvotes: 1