Javascript 从javascript中的变量中删除起始和结束逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5947507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:38:22  来源:igfitidea点击:

remove starting and ending comma from variable in javascript

javascriptjquerystring

提问by Amit

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

我在javascript中有以下变量。我想使用 jquery/javascript 删除开始和结束的“逗号”符号

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

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

please advice

请指教

回答by Gabriele Petrioli

Regex should help

正则表达式应该有帮助

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

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

^,匹配字符串开头,$的逗号并匹配结尾的逗号 ..

回答by Ankit

Below code sample will do this

下面的代码示例将执行此操作

        var str = ",1,2,3,4,5,6,7,8,9,";
        str = str.substring(1,str.lastIndexOf(","));

回答by Josh Leitzel

test.substring(1, test.length - 1);should do it for you.

test.substring(1, test.length - 1);应该为你做。

回答by barcrab

Even easier

更轻松

var result = test.slice(1,-1);