Javascript 如何搜索具有相应文本的特定字符串值
我试图检查字符串数组中是否有匹配的值 所以像这样的方法是有效的Javascript 如何搜索具有相应文本的特定字符串值,javascript,Javascript,我试图检查字符串数组中是否有匹配的值 所以像这样的方法是有效的 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') } 但是,如果您有一个textarea注释,并且您想提到一个具有注释数
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')
}
但是,如果您有一个textarea注释,并且您想提到一个具有注释数据的用户,那么您可以这样做
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
}
演示
当有相应的数据时,如何搜索作为数组的特定值。
indexOf
是我想要使用的方法吗?检查name
是否包括usernames
中的任何用户,如下所示
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');
}
检查
name
是否包括usernames
中的任何用户,如下所示
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');
}
indexOf
将只查找与传递给它的确切对象的匹配项。第一个示例之所以有效,是因为“neo”在usernames
数组中确实作为一个项存在。但是,您的第二个示例失败了,因为数组不包含“@neo you look like the one”的条目
您需要解析名称
字符串并提取用户名,然后使用用户名.indexOf
查看它是否存在。您可以在空格处拆分名称
字符串,然后检查以“@”开头的单词,也可以使用正则表达式
拆分
var用户名=['neo','other'];
var name='@neo你看起来像那个人';
//在每个空格处拆分名称字符串
var splitBySpace=name.split(“”);
//在拆分中从开始处获取每个项目@
//.map使用子字符串(1)删除@前缀
var atNames=splitBySpace.filter(n=>n.indexOf('@')==0.map(n=>n.substring(1));
console.log(atNames[0]);//近地天体
console.log(usernames.indexOf(atNames[0])>=0);//true
indexOf
将仅查找与传递给它的确切对象的匹配项。第一个示例之所以有效,是因为“neo”在usernames
数组中确实作为一个项存在。但是,您的第二个示例失败了,因为数组不包含“@neo you look like the one”的条目
您需要解析名称
字符串并提取用户名,然后使用用户名.indexOf
查看它是否存在。您可以在空格处拆分名称
字符串,然后检查以“@”开头的单词,也可以使用正则表达式
拆分
var用户名=['neo','other'];
var name='@neo你看起来像那个人';
//在每个空格处拆分名称字符串
var splitBySpace=name.split(“”);
//在拆分中从开始处获取每个项目@
//.map使用子字符串(1)删除@前缀
var atNames=splitBySpace.filter(n=>n.indexOf('@')==0.map(n=>n.substring(1));
console.log(atNames[0]);//近地天体
console.log(usernames.indexOf(atNames[0])>=0);//true
用于在文本区域中有多个用户时检查至少一个用户。用于在文本区域中有多个用户时检查至少一个用户。