sugandh goyal
sugandh goyal

Reputation: 323

Regular Expression comparison in js

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

Upvotes: 3

Views: 2997

Answers (3)

jamison
jamison

Reputation: 311

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.

Upvotes: 2

Nate Beers
Nate Beers

Reputation: 1425

you could try:

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

or

if (x.match(rel))

Upvotes: 1

Andrew Leedham
Andrew Leedham

Reputation: 718

You're checking a string against a regexp object, so you'll want something like the following to check RegExp against RegExp:

if(new RegExp(x.value) === re1){
    // Match
}

Upvotes: -2

Related Questions