<!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>
The code in javascript , where I try to compare the x.value with regexp doesn't work. I am trying to make a markdown editor from scratch.Please help me with comparing (#string) with x.value and then output it as H1 heading. While the H2 part works, when I enter (# a).
By using if (x.value==re1), you are attempting to compare the equality of a string and a RegExp object, which will always be false. Instead, use the RegExp object's .test() method:
if (re1.test(x.value))
(see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
RegExp.prototype.test() will perform better in your case than using String.prototype.match(), since the latter (unnecessarily) computes and returns an array of identified matches within the string, when all you need to know is whether or not there was a match.
you could try:
if (x.match(/ ./g))
or
if (x.match(rel))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With