tenub
tenub

Reputation: 3446

JS/jQuery Replacing Part Of Date String Not Working

I have a visible table row containing a table cell with class 'time-col'. In fact I have more than one and the visibility of the parent rows is dynamic.

I am attempting to replace a three character string representation of the month (ie. MAR, APR, etc.) with a numerical string (ie. 3, 4, etc.).

According to my feeble mind the following should work:

$('tr:visible .time-col').each(function() {
    // convert month string to numerical representation
    var monthStr = $(this).text().match(/[^\/]*/)[0];
    var months = { 'JAN': '1', 'FEB': '2','MAR': '3','APR': '4','MAY': '5','JUN': '6','JUL': '7','AUG': '8','SEP': '9','OCT': '10','NOV': '11','DEC': '12' };
    var month = months[monthStr];
    $(this).text( $(this).text().replace(monthStr, month) );
});

but the result replaces the proper string with 'undefined'. Now if I replace the last line:

$(this).text( $(this).text().replace(monthStr, month) );

with:

$(this).text(month);

I get the correct number (ie. 3, 4, etc.) shown in the corresponding table cells.

What gives Stack Overflow?¿

Upvotes: 0

Views: 111

Answers (2)

tenub
tenub

Reputation: 3446

Amazingly I solved the problem on my own. The issue was that for whatever reason JavaScript was not working as I had expected it to, and it decided not to give my number strings in my months object a data type.

Changing:

var month = months[monthStr]

to:

var month = months[monthStr].toString();

solved the problem!

Upvotes: 0

Blender
Blender

Reputation: 298206

$(this).text() returns a string. Modifying that string won't touch the original.

To modify the text, set the text of the element:

var text = $(this).text();
$(this).text(text.replace(monthStr, month));

Also, .replace() with a string as the first argument only replaces the first instance of the string. You'll have to use regex to replace all of the occurrences at once.

Upvotes: 2

Related Questions