2018-09-14 15:52:54 8 Comments

I have created a search mechanism that searches through an array of strings for an exact string match, however I want it to be a bit more intuitive.

I can also get it to search for a string within the string (for example chicken in grilled chicken - however the issue is this allows users to type ken or ill and it returns grilled chicken.

I would like it to return if I typed in chicken or grilled.

Does anyone have any suggestions on how to have a more intuitive search mechanism?


@Matee Gojra 2018-09-14 16:08:34

Try This Simplest Code without Regex

var data = ["first string1", "second string2", "third string3"];
    var wordToSearch = "second";
    var res = null;
    splittedString = strings.split(' ');

@Damian Czapiewski 2018-09-14 16:01:29

I'd use RegExp with word boundary anchor - \b.

function search(query, arr) {
    var res  = [];
    var re = new RegExp('\\b' + query + '\\b');
    arr.forEach(function (item) {
        if (re.test(item)) res.push(item);
    return res;

@Tom 2018-09-14 15:57:19

It sounds like you only want to search by whole words, if that's the case, you could split the string by the space character and then search through the resultant array for matches.

Related Questions

Sponsored Content

41 Answered Questions

[SOLVED] How do I check if an array includes an object in JavaScript?

13 Answered Questions

[SOLVED] How to do case insensitive search in Vim

21 Answered Questions

[SOLVED] In Node.js, how do I "include" functions from my other files?

25 Answered Questions

[SOLVED] Generating random whole numbers in JavaScript in a specific range?

53 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

36 Answered Questions

[SOLVED] How do I check if a string contains a specific word?

14 Answered Questions

[SOLVED] How to check if an element is in an array

  • 2014-06-08 00:52:11
  • jaredsmith
  • 274146 View
  • 392 Score
  • 14 Answer
  • Tags:   arrays swift

74 Answered Questions

[SOLVED] The most elegant way to iterate the words of a string

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2031108 View
  • 2657 Score
  • 74 Answer
  • Tags:   c++ string split

5 Answered Questions

5 Answered Questions

[SOLVED] optimize search through large js string array?

Sponsored Content