-3

I have a string like below.

const a = "The school is big."

And I want to make searching function.

function searching(q){
    ...
}

// searching(the) -> true
// searching(e s) -> true
// searching(oolis) -> true
// searching(the big) -> false        

Could you recommend some solution for this case?

DD DD
  • 1,148
  • 1
  • 10
  • 33
  • 2
    `return a.includes(q)` – Ram Nov 04 '19 at 05:39
  • 1
    You can use `.includes()` if you remove the spaces from your strings – Nick Parsons Nov 04 '19 at 05:39
  • You could use [`indexOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) – Nick Nov 04 '19 at 05:40
  • `oolis` is not in the string, why would that be returning `true`? Is this a typo? – Bilal Ahmed Nov 04 '19 at 05:41
  • Possible duplicate of [How to check whether a string contains a substring in JavaScript?](https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript) – Sheepy Nov 04 '19 at 05:56

2 Answers2

1

If you remove the spaces from both your input string and search string using .replace(), and convert both to lower case using toLowerCase(), then you can use the .includes() method to check if your search string falls within your input string:

const a = "The school is big.";

function searching(str, q) {
  const str_no_space = str.replace(/\s+/g, '').toLowerCase();
  const q_no_space = q.replace(/\s+/g, '').toLowerCase();
  return str_no_space.includes(q_no_space);
}

console.log(searching(a, "the")); // -> true
console.log(searching(a, "e s")); // -> true
console.log(searching(a, "oolis")); // -> true
console.log(searching(a, "the big")); // -> false
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Use includes() and toUpperCase() for case insensitive string comparison.

const a = "The school is big."

function searching(q){
   return a.toUpperCase().includes(q.toUpperCase());
}

console.log(searching('the'));
console.log(searching('e s'));
console.log(searching('oolis'));
console.log(searching('the big'));
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24