0

Here if I try to search with full sentence Search function is not working. Please let me know what is the solution if I need to search with the strings separated by "?"

function myFunction() {
  var str = "How are You? I'm good";
  var n = str.search("How are You? I'm good");
  document.getElementById("demo").innerHTML = n;
}
<button onclick="myFunction()">Try it</button>

<p id="demo"></p>
S.Roy
  • 61
  • 1
  • 5
  • 4
    `search` converts your argument to regex, and `?` has special meaning in regex – Jamiec May 25 '21 at 13:03
  • You pass regex to search, so the questionmark has to be escaped. var str = "How are You? I'm good"; var regex = /[\?]/g; str.search(regex); – oshell May 25 '21 at 13:06
  • 1
    Use `indexOf` instead: `str.indexOf("How are You?")`. If you just want to check if it has a substring, use [`includes`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes) – adiga May 25 '21 at 13:06

1 Answers1

1

Use str.indexOf('How are You? I'm good') if you do not want to use the power of regex. It is faster too.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39