首页 > 解决方案 > 过滤以 JS 开头的值

问题描述

我尝试搜索一个值是否作为第一个单词存在。例如:“我的名字是詹姆斯”,如果我搜索“nam”=> true,如果我搜索“ja”=> true,如果我搜索“ame”则为 false。它的逻辑有效,但我最后没有收到任何物品。

let text = 'ame';
    let option_location = [
       {"text": "James"},
       {"text": "Valkar"},
       {"text": ""},
       {"text": "James2"},
    ];


    // This works but not as I wanted
    let itemsLocation = '';
    itemsLocation = option_location.filter(item => item.text.includes('ame'));
    console.log('Values', itemsLocation);

    // This is not working
    let itemsLocation2 = '';
    itemsLocation2 = option_location.filter(item =>{
        item.text = item.text.toLowerCase();
        let words = item.text.split(" ");
        words.forEach((element,index) => {
            if(element.startsWith(text)){
                return true;
           }else{
                return false;
            }
        });
    });
    console.log('Values', itemsLocation2);

标签: javascript

解决方案


原因是您使用startswith()了检查单词是否以给定字符串开头的函数,该字符串显然name不以ame.

James开始于janame开始于nam

includes()函数只检查单词是否包含给定的字符串,无论它在哪里。


推荐阅读