-4

I want a text to be colored when I type "hello", "Hello", "HELLO", ect.. in an input, it works when I use a string but not as a regex

<input id="input" type="input" value="hello"/>
<span id="result">Hello</span>

<script>   
var input = document.getElementById('input');
var result = document.getElementById('result');
function greenTheTitle(){

        result.style.color = 'green';
    }
function redTheTitle(){

        result.style.color = 'red';
    }

input.addEventListener('keyup', function goodMrn(){
    var inputValue = input.value;
    if(inputValue == /hello/i ){ //does'nt work here
            greenTheTitle();
        }
if(inputValue != /hello/i ){ //and here
            redTheTitle();
        }});    
</script>   

  </body>
</html>

if(inputValue == "hello" ) works but if(inputValue == /hello/i ) doesn't

Antoine
  • 23
  • 1
  • 5

1 Answers1

0

You can't check equality of a string against a RegEx. A RegEx is an object representing a pattern, it is not a string and won't coerce to what you think. (Try it yourself: open your developer console and type /hello/i.toString() and you'll just get the pattern as a string, "/hello/i", which doesn't match the input value.)

What you should be doing is using the Regular Expression test or match functions. Since in this case, you don't need to find which part matched, you can just use test, which returns true if the string matches somewhere and false if it doesn't.

if (/hello/i.test(inputValue)) { /* ... */ }

Note this will match the string "hello" anywhere inside the input as well, so it'll match "well hello there", "dsjnbdjkasbdjhellojbasdjhsbja", etc. You can fix this by anchoring your regex at the beginning and end, like this:

if (/^hello$/i.test(inputValue)) { /* ... */ }

That means "the string starts with (^) hello and then ends ($)". Or, if all you want is case-insensitivity, then maybe you don't even need to use a RegEx here. You can just make the input lower-case and compare to a lower-case string:

if (inputValue.toLowerCase() === 'hello') { /* ... */ }
IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26