Blynn
Blynn

Reputation: 1421

Replace and Add Wrapper with Javascript / JQuery

I'm starting with some date that I cannot format the way I want, so I'm trying to format via javaScript.

<div class="date">
Oct. 07,
</div>

And I'm trying to achieve:

<div class="date">
<div class="m1">Oct</div> <div class="m2">07</div>
</div>

I have this jQuery, but I'm not close yet

$(document).ready(function() {

$('.date').each(function( index ) {
var kill = $(this).html().replace(/. /g, ' ').replace(/,/g,' ');
$(this).html(kill);
});

});

Upvotes: 1

Views: 174

Answers (3)

Kris Erickson
Kris Erickson

Reputation: 33844

var $date = $('.date'),
    text = $date.text(),
    monthYear = text.split('.');
$date.html('')
    .append($('<div class="m1">' + monthYear[0] + '</div>'))
    .append($('<div class="m2">' + monthYear[1].replace(',','') + '</div>'));

Fiddle

Upvotes: 2

The Alpha
The Alpha

Reputation: 146239

You may try this too

var date = $.trim($('.date').text()), d = date.split('.');
$('.date').html("<div class='m1'>"+d[0]+"</div> <div class='m2'>"+d[1].replace(',', '')+"</div>");

DEMO.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

Try

$('.date').html(function (idx, html) {
    return html.replace(/([a-z]+).(\s+)(\d+),/i, '<div class="m1">$1</div> <div class="m2">$3</div>')
})

Demo: Fiddle

Upvotes: 1

Related Questions