<!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对象的相等性,后者始终为false。而是使用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/