Remove last character

  • Hari Narayanan
  • Graduate
  • Graduate
  • Hari Narayanan
  • Posts: 103

Post 3+ Months Ago

Hi all

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

How do I remove only the last comma
from the string using Javascript ?
  • Hari Narayanan
  • Graduate
  • Graduate
  • Hari Narayanan
  • Posts: 103

Post 3+ Months Ago

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
  • Posts: 1853

Post 3+ Months Ago

Or just:

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


Negative numbers give offsets from the back of the string.
  • mwafi
  • Born
  • Born
  • mwafi
  • Posts: 1

Post 3+ Months Ago

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
  • clivepaterson
  • Posts: 1

Post 3+ Months Ago

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
  • Posts: 127
  • Loc: Bangalore

Post 3+ Months Ago

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 65 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
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.