1

I am trying to target every space and hyphen within a string and wrap each word with a span. This is what I am trying, obviously is not the best way to achieve this. Any ideas?

$('.whatsOn').each(function() {
    var date = $(this).find(".time");
    var words = date.text().split(" ");
    date.empty();
    $.each(words, function(i, v) {
       date.append($("<span>").text(v));
    });
  
    var wordsSpan = $(this).find(".time span").text().split("-");
    $(this).find(".time span").empty();
    $.each(words, function(i, v) {
       $(this).find(".time span").append($("<span>").text(v));
    });
});
<div class="whatsOn">
   <dd class="time">14th-29th July</dd>
</div>
rrk
  • 15,677
  • 4
  • 29
  • 45
patie
  • 300
  • 2
  • 5
  • 21

2 Answers2

2

You can pass regular expression to split like this. date.text().split(/[- ]/);

$('.whatsOn').each(function() {
  var date = $(this).find(".time");
  var words = date.text().split(/[- ]+/);
  console.log(words)
  date.empty();
  $.each(words, function(i, v) {
    date.append($("<span>").text(v));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<dl class="whatsOn">
  <dd class="time">14th-29th July</dd>
</dl>
rrk
  • 15,677
  • 4
  • 29
  • 45
1

In this case, you can use regular expression to split the string.

var words = date.text().split(/[\s-]+/);
Tang Chanrith
  • 1,219
  • 12
  • 8