<!DOCTYPE html>
<html>
<head>
<title>hhh</title>
</head>
<body>
<input type="text" id="fname" onkeyup="myFunction()">
<script>
function myFunction() {
var re1 =/./;
var x = document.getElementById("fname");
if(x.value==re1){
var h = document.createElement("H1");
var t = document.createTextNode(x.value);
h.appendChild(t);
document.body.appendChild(h);}
else if (x.value=="## a"){
var h = document.createElement("H2");
var t = document.createTextNode(x.value);
h.appendChild(t);
document.body.appendChild(h);}
}
</script>
</body>
javascript 中的代码,我尝试将 x.value 与 regexp 进行比较的代码不起作用。我正在尝试从头开始制作 Markdown 编辑器。请帮助我将 (#string) 与 x.value 进行比较,然后将其输出为 H1 标题。 当 H2 部分工作时,当我输入 (# a) 时。
最佳答案
通过使用 if (x.value==re1)
,您试图比较字符串和 RegExp 对象的相等性,这始终为假。相反,使用 RegExp 对象的 .test()
方法:
if (re1.test(x.value))
(参见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
RegExp.prototype.test() 在您的情况下比使用 String.prototype.match() 执行得更好,因为后者(不必要地)计算并返回字符串中已识别匹配的数组,而您只需要知道是否匹配。
关于javascript - js中的正则表达式比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42166490/