Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression comparison in js

Tags:

javascript

<!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).

like image 669
sugandh goyal Avatar asked Dec 21 '25 11:12

sugandh goyal


2 Answers

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.

like image 126
jamison Avatar answered Dec 22 '25 23:12

jamison


you could try:

if (x.match(/ ./g))

or

if (x.match(rel))
like image 42
Nate Beers Avatar answered Dec 22 '25 23:12

Nate Beers