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" 开发者_Go百科sign using jquery/javascript
var test=",1,2,3,4," <---
Expected output: var test="1,2,3,4"
please advice
Regex should help
var edited = test.replace(/^,|,$/g,'');
^,
matches the comma at the start of the string and ,$
matches the comma at the end ..
Below code sample will do this
var str = ",1,2,3,4,5,6,7,8,9,";
str = str.substring(1,str.lastIndexOf(","));
test.substring(1, test.length - 1);
should do it for you.
Even easier
var result = test.slice(1,-1);
精彩评论