Regular Expressions
Declarative Programming
Advanced Language Features
Fundamentals
Strings

replace seems like the perfect tool for the job in this case.

This version is in a one-liner format but could pretty easily be split on multiple lines for clarity.

There are also some potential very slight performance improvements as it does not need to create a temporary array in memory and the inner word/digit test only checks the first character (but this is likely irrelevant in most real-world use cases)

Code
Diff
  • let transformText = s => s.replace(/\D+|[\d.]+/g, m => /^\D/.test(m) ? (m = m.trim()) && `<span>${m}</span>` : `<div>${m}</div>`);
  • 1
    function transformText(s) {
    
    2
      return s.split(/(\d+)/)
    
    3
        .map(w => w.trim())
    
    4
        .filter(w => w)
    
    5
        .map(w => (
    
    6
          /\d/.test(w) ? `<div>${w}</div>` : `<span>${w}</span>`
    
    7
        ))
    
    8
        .join``;
    
    9
    }
    
    1+
    let transformText = s => s.replace(/\D+|[\d.]+/g, m => /^\D/.test(m) ? (m = m.trim()) && `<span>${m}</span>` : `<div>${m}</div>`);