Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove last comma from the string using jQuery

Tags:

jquery

I am storing multiple selected option value to the textbox and concatenate with comma but dont want to add in last of the string. hear is my code.

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<select id="garden" name="garden" multiple="multiple">
  <option value="1">Flowers</option>
  <option value="2">Shrubs</option>
  <option value="3">Trees</option>
  <option value="4">Bushes</option>
  <option value="5">Grass</option>
  <option value="6">Dirt</option>
</select>
<input type="text" name="store" id="store" />
<script>
$("#garden").change(function () {
  var str = "";
  $("select option:selected").each(function () {
        str += $(this).val() + ",";
      });
    $('#store').val(str).attr('rows',str.length) ;
})
.trigger('change');
</script>
</body>
</html>
like image 504
lumos Avatar asked Jan 11 '13 11:01

lumos


People also ask

How do I remove a trailing comma in typescript?

To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second. The method will return a copy of the string without the leading or trailing comma. Copied!

How do I remove the last line of a comma in Unix?

Using awk and tac : The awk command is a simple one to do the substitution the first time the pattern is seen. tac reverses the order of the lines in the file, so the awk command ends up removing the last comma. may be more efficient. Save this answer.


2 Answers

You could do this using .substring():

 $('#store').val(str.substring(0,str.length-1)).attr('rows',str.length-1) ;
like image 59
A. Wolff Avatar answered Sep 28 '22 02:09

A. Wolff


simply use,

in palce of this

         $('#store').val(str).attr('rows',str.length) ; 

use

         str=str.slice(0,-1); 

This is enough to omit the last comma.

like image 28
jaydeep Avatar answered Sep 28 '22 03:09

jaydeep