Sunday, April 1, 2012

JAVASCRIPT - How to remove last character from string

A common requirement, I have been approached is to have a javascript function to remove last character of a string. This is usually for some delimited string like a comma separated string.

var yourStr = "1, 2, 3, 4,"    
var yourstrLen =  yourStr.length;
yourStr =  yourStr.slice(0,yourstrLen-1);
alert (yourStr);

Instead of 
    yourStr.slice(0, 1); is also equally acceptable, because negative value sets offset from the end of the string.

No comments:

Post a Comment