简体   繁体   English

在字符串中查找整个单词 - Javascript

[英]Find a whole word in a string - Javascript

I want a method that finds a word in a string, it have to be a whole array, not subarray on a string(as array.includes() does)我想要一个在字符串中找到单词的方法,它必须是一个完整的数组,而不是字符串的子数组(就像 array.includes() 那样)

const key = ['one','two','three']
let message = 'onepiece'

    key.forEach((j) => {
    //string.prototype.includes()
    if(message.includes(j)) console.log('Method1',true); //In this way is true always there is a 'one', no matter if the string is just 'one' or 'onepiece' or 'one piece'
    else  console.log('Method1',false)
    
    //array.prototype.includes()
    if(j.includes(message)) console.log('Method2',true); //In this way is true when message = 'one'
    else  console.log('Method2',false)
});

The following code does what I want下面的代码做我想要的

const key = ['one','two','three']
let message = 'one'

    for (var i=0 ; message[i]!=undefined ; i++){
        mes = message.split(" ")[i]
        if(key.includes(mes)) console.log(true) //In this way is true when the message contains 'one', no matter if it's alone or in a string, but false if it's 'onepiece'
    }

I feel this code is highly inefficient, my question is there a simpler way to do this function?我觉得这段代码效率很低,我的问题是有没有更简单的方法来做到这一点 function?

Thx!谢谢!

Sounds like you are looking for intersection between two arrays since you are treating messsage as an array by splitting it.听起来您正在寻找两个messsage之间的交集,因为您通过拆分消息将其视为一个数组。 In that case you could use array.some() to check if any words in key exist in message :在这种情况下,您可以使用array.some()检查message中是否存在key中的任何单词:

 const key = ['one', 'two', 'three'] let message = 'one' let mes = message.split(' ') let result = key.some(val => mes.includes(val)) console.log(result) //Result is true for 'one' //Result is true for 'one piece' //Result is false for 'onepiece'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM