Javascript 搜索匹配项并输出匹配词所在的整个字符串

Javascript Search for a match and output the whole string that the matching word is apart of

您将如何输出找到的输出,包括字符串的其余部分?该数组只是充满了字符串。谢谢

    var searchingfor = document.getElementById('searchfield').value;
        var searchingforinlowerCase = searchingfor.toLowerCase();
        var searchDiv = document.getElementById('searchDiv');
        var convertarraytoString = appointmentArr.toString();
        var arraytolowerCase = convertarraytoString.toLowerCase();
        var splitarrayString = arraytolowerCase.split(',')



        if(search(searchingforinlowerCase, splitarrayString) == true) {
                alert( searchingforinlowerCase + ' was found at index' + searchLocation(searchingforinlowerCase,splitarrayString) + ' Amount of times found = ' +searchCount(searchingforinlowerCase,splitarrayString));


        function search(target, arrayToSearchIn) {

        var i;

          for (i=0; i<arrayToSearchIn.length; i++)
        {   if (arrayToSearchIn[i] == target && target !=="")
        return true;
        }

你可以这样做

var test = 'Hello World';
if (test.indexOf('Wor') >= 0)
{
  /* found substring Wor */
}

在您发布的代码中,您将数组转换为字符串,然后再次使用 split() 将其转换回数组。那是不必要的。搜索可以调用为

search(searchingforinlowerCase, appointmentArr);

试试这个

if(search(searchingforinlowerCase, appointmentArr) == true) {
                    alert( searchingforinlowerCase + ' was found at index' + searchLocation(searchingforinlowerCase,splitarrayString) + ' Amount of times found = ' +searchCount(searchingforinlowerCase,splitarrayString));


function search(target, arrayToSearchIn) {
var i; 
for (i=0; i<arrayToSearchIn.length; i++)
{   if (arrayToSearchIn[i].indexOf(target >= 0))
        return true;
}
    return false;
}

此代码将帮助您找到匹配项。您可以更新代码以显示找到匹配项的全文。原始发布的代码比较整个字符串而不是部分匹配。

尝试利用 Array.prototype.filter() , String.prototype.indexOf()

// input string
var str = "america";
// array of strings
var arr = ["First Name: John, Location:'america'", "First Name: Jane, Location:'antarctica'"];
// filter array of strings
var res = arr.filter(function(value) {
  // if `str` found in `value` , return string from `arr`
  return value.toLowerCase().indexOf(str.toLowerCase()) !== -1
});
// do stuff with returned single , or strings from `arr`
console.log(res, res[0])

以下将在字符串数组中查找一个单词,return 匹配该单词的所有字符串。这是您要找的东西吗?

var a  = ["one word", "two sentence", "three paragraph", "four page", "five chapter", "six section", "seven book", "one, two word", "two,two sentence", "three, two paragraph", "four, two page", "five, two chapter",];

function search(needle, haystack){
    var results = [];
  haystack.forEach(function(str){
        if(str.indexOf(needle) > -1){
            results.push(str);
        }
  });
    return results.length ? results : '';
};

var b = search("word", a);
console.log(b);

这里是 fiddle 尝试。