Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove starting and ending comma from variable in javascript

i have the below variable in javascript. i want to remove the starting and ending "comma" sign using jquery/javascript

var test=",1,2,3,4," <--- 

Expected output: var test="1,2,3,4"

please advice

like image 825
Amit Avatar asked May 10 '11 08:05

Amit


People also ask

How do I remove a trailing comma from a string?

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.

How do you replace last comma with and?

replace(/,([^,]*)$/, 'and $1'); This will find the last comma in a string and replace it with "and" and anything that came after it.

How do I remove the last comma from a string in HTML?

To remove the last comma of a string in JavaScript, we can use the built-in slice() method by passing the 0, -1 as arguments to it. In the slice() method, negative indexes are used to access the characters from the end of a string.


1 Answers

Regex should help

var edited = test.replace(/^,|,$/g,'');

^, matches the comma at the start of the string and ,$ matches the comma at the end ..

like image 86
Gabriele Petrioli Avatar answered Oct 05 '22 19:10

Gabriele Petrioli