1

How would you insert substrings between elements using regular expressions or an alternative form in javascript/jQuery?

For example I have the following string:

This is a string 015 with numbers 1486453 randomly 10 inserted between words 0954

If my regex is to find all numbers, the result would be the following:

This is a string <span>015</span> with numbers <span>1486453</span> randomly <span>10</span> inserted between words <span>0954</span>

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
cooxie
  • 2,934
  • 5
  • 18
  • 17

2 Answers2

5
var testStr = 'This is a string 015 with numbers 1486453 randomly 10 inserted between words 0954';    
var result = testStr.replace(/(\d+)/gi, '<span>$1</span>');
jay c.
  • 1,521
  • 10
  • 9
0
var str = $el.text();
$el.html(str.replace(/\d+/g, "<span>$&</span>"));

If your element already contains html nodes, it gets more complicated. You'd need to build a DOM iterator - see this answer.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375