Jon Jon - 5 months ago 12
HTML Question

How to underline numbers in an input or textarea using Javascript

So I have a textarea inputbox and I want to know is there any way to underline the number values in this input box than using regular expressions (I don't really understand them).

here's my changeAll() function that does nothing really but get the value from the input box and it will change a different div element(my output box) to the newly underlined output:

changeAll = function(){
var x = document.getElementById('input').value;
//underline numbers ....
document.getElementById('demo').innerHTML = y;
}


I also know that the CSS is just

#number {
text-decoration: underline;
}


Any help on how to do this in an easier way than regular expressions would be much appreciated.

Answer

With a regular expression:

var input = document.getElementById("input");
var output = document.getElementById("output");

input.addEventListener("keyup", function () {
  output.innerHTML = input.value.replace(
    /(\d+)/g, "<span style=\"text-decoration:underline\">$1</span>"
  );
});
<textarea id="input"></textarea>
<div id="output"></div>

Without a regular expression:

var input = document.getElementById("input");
var output = document.getElementById("output");

input.addEventListener("keyup", function () {
  var open = false;
  var digit = false;
  var x = this.value, y = "";
  var i, n = x.length;
  for (i = 0; i < n; i++) {
    digit = x[i] >= '0' && x[i] <= '9';
    if (digit && !open) {
      open = true;
      y += "<span style=\"text-decoration:underline\">";
    } else if (!digit && open) {
      open = false;
      y += "</span>";
    }
    y += x[i];
  }
  output.innerHTML = y;
});
<textarea id="input"></textarea>
<div id="output"></div>

Comments