如何使用javascript标记数字

时间:2016-10-01 08:57:12

标签: javascript numbers

我需要在HTML页面上标记数字。我知道如何标记数字,但我如何识别十进制数字?我需要标记范围内的每个数字。像这样:[范围1-3]

This is number 1, this is number 1.8 and this is 8.2. It should also mark number 3.

如何使用javascript(不使用jQuery)标记它?

谢谢,彼得

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式来更改数字。

var node = document.getElementById('text');

node.innerHTML = node.innerHTML.replace(/(\d+(\.\d+)?)+/g, function (s) {
    return s >= 1 && s <= 3 ? '<strong>' + s + '</strong>' : s;
});
<div id="text">This is number 1, this is number 1.8 and this is 8.2. It should also mark number 3.</div>

答案 1 :(得分:1)

您可以拆分字符串并在循环中找到符合条件的数字

var div = document.getElementById("div");
div.innerHTML = div.innerHTML.split(/\s/)
  .map(v => {
    if (!isNaN(parseFloat(v)) && parseFloat(v) <= 3) {
      var res = parseFloat(v);
      var rest = new RegExp(res, "g");
      return "<strong>" + res + "</strong>" + v.replace(rest, "");
    }

    return v;
  }).join(" ");
<div id="div">
This is number 1, this is number 1.8 and this is 8.2. It should also mark number 3.
</div>