在JavaScript中将字符串转换为正则表达式
我想在键入hello、hello、hello等时对文本进行着色。。在输入中,它在我使用字符串而不是正则表达式时工作在JavaScript中将字符串转换为正则表达式,javascript,regex,Javascript,Regex,我想在键入hello、hello、hello等时对文本进行着色。。在输入中,它在我使用字符串而不是正则表达式时工作 <input id="input" type="input" value="hello"/> <span id="result">Hello</span> <script> var input = document.getElementById('input'); var result = document.getElemen
<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>
ifinputValue==你好工作
但是
ifinputValue==/hello/i不您不能根据正则表达式检查字符串的相等性。正则表达式是一个表示模式的对象,它不是字符串,也不会强制执行您的想法。自己试试:打开开发人员控制台并键入/hello/i.toString,您将得到一个字符串形式的模式,/hello/i,它与输入值不匹配 您应该使用正则表达式测试或匹配函数。因为在这种情况下,您不需要找到匹配的部分,您可以使用test,如果字符串在某个地方匹配,它将返回true,如果不匹配,则返回false
if (/hello/i.test(inputValue)) { /* ... */ }
请注意,这也将匹配输入中任何位置的字符串hello,因此它将很好地匹配hello there、dsjnbdjkasbdjhellojbasdjhsbja等。您可以通过在开头和结尾锚定正则表达式来解决此问题,如下所示:
if (/^hello$/i.test(inputValue)) { /* ... */ }
这意味着字符串以^hello开头,然后以$结尾。或者,如果您只想区分大小写,那么您甚至不需要在这里使用正则表达式。您只需将输入设置为小写,并与小写字符串进行比较:
if (inputValue.toLowerCase() === 'hello') { /* ... */ }
字符串不是正则表达式,因此不能像那样使用==运算符。您很可能需要像/hello/i.testInputValue这样的内容谢谢Dean Taylor,它可以工作: