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
  • 98,378
  • 36
  • 187
  • 224
cooxie
  • 2,804
  • 4
  • 17
  • 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,481
  • 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
  • 572,313
  • 128
  • 898
  • 1,281