user6792802
user6792802

Reputation:

JavaScript; REGEX between delimiters and separate by space

I have this code:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    window.onload = function() {
        var e = document.getElementById("first"), n=document.getElementById("second");
        e.addEventListener("input", function() {
            n.value = e.value.match( /\<span class="my_class">(.+)\<\/span>/ )[1]
        })
    };
</script>
</head>
<body>

<input class="textfield" id="first"><br><br>
<input class="textfield" id="second">

</body>
</html>

When you insert <span class="my_class">test</span> in first field, second field will output test. This is exactly what I want.

But if I insert e.g. <span class="my_class">test</span> some text<span class="my_class">hello</span> I'm getting test</span> some text<span class="my_class">hello instead of test hello (separated by a space).

What am I doing wrong?

Upvotes: 0

Views: 51

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

Use jquery construct to parse the HTML and get the value inside the markup span

DEMO

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
  <script>
    window.onload = function() {
      var e = document.getElementById("first"),
        n = document.getElementById("second");
      e.addEventListener("input", function() {
        var valueArr = [];
        $(e.value).each(function(v, i) {
          if (i.nodeName == "SPAN" && i.classList.contains( "my_class" ) ) {
            valueArr.push($(i).text());
          }
        });
        n.value = valueArr.join(" ");
      })
    };
  </script>
</head>
<body>
  <input class="textfield" id="first"><br><br>
  <input class="textfield" id="second">
</body>
</html>

Upvotes: 2

Related Questions