tags:

views:

51

answers:

4

Hi I have written a function that is used to change text in a table cell, the table displays members of a team but is not in a readable format, so i have to convert the string output into a readable format.

This all works fine however I was wondering if anyone could help me re-factor this function as it seems abit crude ?

Jquery Code:

$(".membersName").each(function() {

   var memberName = $(this).text();
   var splitmemberName = memberName.split("=");
   var finalNameSplit = splitmemberName[1].split(",");
   $(this).empty();
   $(this).append(finalNameSplit[0]);


});

Any help or tips would be greatly appreciated. Cheers in advance

+3  A: 

Looks fine to me! You could use RegExp instead, but I can't say that would be better. Although this:

$(this).empty(); 
$(this).append(finalNameSplit[0]); 

Could be shortened up to this:

$(this).empty().append(finalNameSplit[0]); 
Josh Stodola
Brilliant cheers Josh !
jonathan p
Note: you could technically combine the entire function into one line of code if you wanted. However, that would be less readable more difficult to maintain. The way you have it now is a good balance.
Josh Stodola
A: 

Chaining can help you a bit in places, for example:

$(this).empty();
$(this).append(finalNameSplit[0]);

Can become

$(this).empty().append(finalNameSplit[0]);

Also, try caching $(this) for increased performance, i.e.

var $this = $(this);

Technically, you could amalgamate these lines:

var memberName = $(this).text();
var splitmemberName = memberName.split("=");
var finalNameSplit = splitmemberName[1].split(",");

Like so:

var finalNameSplit = $(this).text().split("=")[1].split(",");

Which means you could write it in one line of code:

$(this).empty().append($(this).text().split("=")[1].split(",")[0]);

Although your version is much more readable.

James Wiseman
Brilliant cheers James, definitely some food for thought !
jonathan p
James - You are performing an `.empty()` *before* you are getting the text. As such, there will be no text left to manipulate. :o)
patrick dw
+1  A: 

just one:

$(".membersName").html(function(i, old) {
    var eqpos = old.indexOf("=");
    return old.substring(eqpos+1, old.indexOf(",", eqpos));
});​
galambalazs
You could be more jQuery with this answer and use $(this).html() instead.
James Wiseman
+2  A: 

Try this: http://jsfiddle.net/C9fMN/

$(".membersName").each(function() {
    $(this).text(function(i,txt) {
        return txt.split("=")[1].split(",")[0];
    });
});

No need to use .empty() this way, since you're replacing the text altogether.

In fact, this way, you really don't even need the call to .each():

http://jsfiddle.net/C9fMN/1/

$('.membersName').text(function(i,txt) {
    return txt.split("=")[1].split(",")[0];
});
patrick dw