How to take out the number in the text of the dom element and then change the color of the number

problem description

A text such as "my 123MediaTek 456 grandiose 789", take 123456789 out to form an array or other data type, then change the color of 123456789, and then put it back, can this function be realized?


https://codepen.io/littlelyon.


regular string substitution ~ number with a tag < span style=" color:red; "> 123


is not proficient in regularization, but it is also implemented:

        <style>
        .onlyone{
            color: red;
        }
    </style>
    <div id="div">
        123456789
    </div>
    
    <script>
        var ins = document.getElementById('div');
        var arr = ins.innerText.match(/\d{1,}/g);
        ins.innerHTML = ins.innerText.replace(/\d{1,}/g,'<span class="onlyone"></span>')
        var el = document.querySelectorAll('.onlyone');
        el.forEach(function(item,i){
            item.innerText = arr[i]
        })
    </script>

HTML

<p id="demo">
  123456789

STYLE

<style type="text/css">
    -sharpdemo span {
        color: red;
    }
</style>

JS

let text = document.getElementById("demo").innerText;
let html = text.replace(/(\d+)/g, `<span>$1</span>`);
document.getElementById("demo").innerHTML = html;
Menu