user1209945
user1209945

Reputation: 81

Add a span tag to certain characters in a string with javascript/jquery

I have output from a CMS where I need to add a style to a certain character in the string. For instance, my output is:

 <div class="date">12 // 14 // 2013</div>

How can I add:

<span style="slashColor"> 

to the two double slashes so that my result would be:

<div class="date">12 <span class="slashColor">//</span> 14 <span class="slashColor">//</span> 2013</div>

Upvotes: 0

Views: 4900

Answers (2)

Sergio
Sergio

Reputation: 28845

Try this:

var original = $('.date').text();
var new_version = original.split('//').join('<span class="slashColor">//</span>');
$('.date').html(new_version);

Fiddle

If you have many div like the example you posted, you can use this:

$('.date').each(function () {
    var original = $(this).text();
    var new_version = original.split('//').join('<span class="slashColor">//</span>');
    $(this).html(new_version)
});

Fiddle

Upvotes: 3

Maciej Łebkowski
Maciej Łebkowski

Reputation: 3942

var elements = document.getElementsByClassName('date');
for (var i = 0, e; e = elements[i++]; ) {
   e.innerHTML = e.innerHTML.replace(/\/\//g, '<span class="slashColor">//</span>');
}

or the jQuery way:

$('.date').each(function () {
  $(this).html($(this).html().replace(/\/\//g, '<span class="slashColor">//</span>'));
}

Upvotes: 1

Related Questions