Zhurovich
Zhurovich

Reputation: 75

How can I change a string using javascript/jquery?

I have a string Feb 2012. How can I convert it to FEBRUARY 2012. Actually I have a whole array ['Jan 2011', 'Feb 2011', 'Mar 2011', ... ] I need to convert each element and get ['JANUARY 2011', ...]

Upvotes: 2

Views: 105

Answers (5)

palaѕн
palaѕн

Reputation: 73896

Try this using jQuery:

var arr = ["Jan 2011", "Feb 2011", "Mar 2011"];
var name = ["JANUARY", "FEBRUARY", "MARCH"];
var list = new Array();

// Loop through the array arr
$.each(arr, function(i, value) {

    // Convert the month names
    var month = name[i];
    var year = value.split(" ")[1];

    // Display the result
    alert(month + ' ' + year);  

    // Add elements to a new array
    list.push(month + ' ' + year);
});​

console.log(list);

Console Result:

["JANUARY 2011", "FEBRUARY 2011", "MARCH 2011"]

Hope this helps!

Upvotes: 0

Ash
Ash

Reputation: 3166

If you're going to be doing other time and date based manipulations in your app, I'd recommend using Moment.js (http://momentjs.com/). It's a really powerful library - perhaps a little too much so if this is all you need to do - but worth looking into anyway.

To answer your question with Moment.js, this is the snippet you'd need:

moment('Feb 2011', 'MMM YYYY').format('MMMM YYYY').toUpperCase();
// FEBRUARY 2011

Upvotes: 0

Burlak Ilia
Burlak Ilia

Reputation: 150

var dt = new Date("Feb 2012"), // FEBRUARY 2012
    m_names = ["JANUARY", "FEBRUARY", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December"];

var curr_month = dt.getMonth(),
    curr_year = dt.getFullYear();

console.log(m_names[curr_month] + " " + curr_year);

Upvotes: 1

jcolicchio
jcolicchio

Reputation: 808

var myDate = new Date(Date.parse("Mar 2012"));
var monthNum = myDate.getMonth();
var year = myDate.getFullYear();

Now turn the monthNum into a string. I suggest an array of 12 strings, and array[monthNum] to get the proper one.

Upvotes: 0

syazdani
syazdani

Reputation: 4868

Assuming the strings are always formatted as '{monthShortForm} {year}', you can do the following:

var input = 'Jan 2011';
var parts = input.split(' ');
var output = longForm[parts[0].toLowerCase()] + ' ' + parts[1];

where longForm is a map like so

longForm = { 'jan': 'JANUARY', 'feb': 'FEBRUARY', /* etc */ };

Hope that helps.

Upvotes: 7

Related Questions