javascript - Remove Last Comma from a string -


using javascript, how can remove last comma, if comma last character or if there white space after comma? code. got working fiddle. has bug.

var str = 'this, test.';  alert( removelastcomma(str) ); // should remain unchanged  var str = 'this, test,';  alert( removelastcomma(str) ); // should remove last comma  var str = 'this test,          ';  alert( removelastcomma(str) ); // should remove last comma  function removelastcomma(strng){             var n=strng.lastindexof(",");     var a=strng.substring(0,n)      return a; } 

this remove last comma , whitespace after it:

str = str.replace(/,\s*$/, ""); 

it uses regular expression:

  • the / mark beginning , end of regular expression

  • the , matches comma

  • the \s means whitespace characters (space, tab, etc) , * means 0 or more

  • the $ @ end signifies end of string


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -