You cannot compare document.getElementById("demo") directly with result. document.getElementById("demo") returns an HTMLElement, while result is an array.
Also, you're checking the contents of the element after you've already set it. In that case, the if statement will always evaluate to true and the if block will always execute, meaning that the text will never appear (it will be set and instantaneously removed).
Also, to remove the text, you'll need to set .innerHTML to an empty string (""), not the element to "0".
The most minimal way to get your code working:
function myFunction() {
var str = "Visit W3Schools";
var patt = /w3schools/i;
var result = str.match(patt);
if (document.getElementById("demo").innerHTML == result) {
document.getElementById("demo").innerHTML = "";
} else {
document.getElementById("demo").innerHTML = result;
}
}
<p>Click the button to do a case-insensitive search for "w3schools" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Now, there are a couple of other improvements that could be made to your code.
document.getElementById() is a bit slow, so you want to just get the element once, assign it to a variable, and then use that variable instead.
Also, it's generally considered a bad practice to use ==, === is preferred whenever possible. However, if you change == to === in your code, it won't work correctly. The reason is that str.match(patt) actually returns an array with one item. When you assign it to .innerHTML the browser converts it to a string, which works fine. However, when you compare .innerHTML with result, the one is a string, the other is an array, so they don't match with ===. The solution is to do var result = str.match(patt)[0];, since you're only interested in the first match (remember, arrays are zero-indexed, so the first item is 0, not 1).
With these edits, your code would read:
function myFunction() {
var str = "Visit W3Schools";
var patt = /w3schools/i;
var result = str.match(patt)[0];
var demo = document.getElementById("demo")
if (demo.innerHTML === result) {
demo.innerHTML = "";
} else {
demo.innerHTML = result;
}
}
<p>Click the button to do a case-insensitive search for "w3schools" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>