Ad
Regular Expressions
Declarative Programming
Advanced Language Features
Programming Paradigms
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>`);
    • function transformText(s) {
    • return s.split(/(\d+)/)
    • .map(w => w.trim())
    • .filter(w => w)
    • .map(w => (
    • /\d/.test(w) ? `<div>${w}</div>` : `<span>${w}</span>`
    • ))
    • .join``;
    • }
    • let transformText = s => s.replace(/\D+|[\d.]+/g, m => /^\D/.test(m) ? (m = m.trim()) && `<span>${m}</span>` : `<div>${m}</div>`);