Remove last character

  • Hari Narayanan
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Jun 07, 2005
  • Posts: 103
  • Status: Offline

Post June 27th, 2005, 1:43 am

Hi all

I have a string :
One, Two, Three, Four,

How do I remove only the last comma
from the string using Javascript ?
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post June 27th, 2005, 1:43 am

  • Hari Narayanan
  • Graduate
  • Graduate
  • No Avatar
  • Joined: Jun 07, 2005
  • Posts: 103
  • Status: Offline

Post June 27th, 2005, 1:56 am

Got it ...

JAVASCRIPT Code: [ Select ]
var myStr = "One, Two, Three, Four,"     
var strLen = myStr.length;
myStr = myStr.slice(0,strLen-1);
alert (myStr);
  1. var myStr = "One, Two, Three, Four,"     
  2. var strLen = myStr.length;
  3. myStr = myStr.slice(0,strLen-1);
  4. alert (myStr);
  • Mas Sehguh
  • Mastermind
  • Mastermind
  • User avatar
  • Joined: Aug 07, 2004
  • Posts: 1853
  • Status: Offline

Post June 27th, 2005, 6:31 am

Or just:

Code: [ Select ]
myStr = myStr.slice(0, -1)


Negative numbers give offsets from the back of the string.
  • mwafi
  • Born
  • Born
  • No Avatar
  • Joined: Jun 26, 2009
  • Posts: 1
  • Status: Offline

Post October 19th, 2009, 10:55 am

Mas Sehguh wrote:
Or just:

Code: [ Select ]
myStr = myStr.slice(0, -1)


Negative numbers give offsets from the back of the string.

thx :D
  • clivepaterson
  • Born
  • Born
  • No Avatar
  • Joined: Sep 29, 2011
  • Posts: 1
  • Status: Offline

Post September 29th, 2011, 8:05 pm

This will work if you're unsure that there is a comma, you can change the regex to cater for many scenarios.
JAVASCRIPT Code: [ Select ]
myStr = myStr.replace(/,$/,'');
  • Satwant
  • Graduate
  • Graduate
  • User avatar
  • Joined: Dec 27, 2010
  • Posts: 126
  • Loc: Bangalore
  • Status: Offline

Post September 29th, 2011, 11:14 pm

If you like you can first remove the trailing spaces, newline etc from your string using this function so that above mention solution
JAVASCRIPT Code: [ Select ]
myStr = myStr.slice(0, -1)


can work without trouble.
JAVASCRIPT Code: [ Select ]
 
function rtrim(str, chars) {
   chars = chars || "\\s";
   return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
 
  1.  
  2. function rtrim(str, chars) {
  3.    chars = chars || "\\s";
  4.    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
  5. }
  6.  

Post Information

  • Total Posts in this topic: 6 posts
  • Users browsing this forum: No registered users and 290 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.