Javascript 如果是逗号,则从字符串中删除第一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2182596/
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
Remove first character from a string if it is a comma
提问by kwhohasamullet
I need to setup a function in javascript to remove the first character of a string but only if it is a comma ,. I've found the substrfunction but this will remove anything regardless of what it is.
我需要在 javascript 中设置一个函数来删除字符串的第一个字符,但前提是它是一个逗号,。我找到了这个substr函数,但这会删除任何东西,不管它是什么。
My current code is
我目前的代码是
text.value = newvalue.substr(1);
回答by jensgram
text.value = newvalue.replace(/^,/, '');
Edit: Tested and true. This is just oneway to do it, though.
编辑:经过测试且属实。不过,这只是一种方法。
回答by Max Shawabkeh
s = (s.length && s[0] == ',') ? s.slice(1) : s;
Or with a regex:
或者使用正则表达式:
s = s.replace(/^,/, '');
回答by Jimmy Cuadra
var result = (myString[0] == ',') ? myString.substr(1) : myString;
回答by Leo Tahk
thanks for the tips, got a working code here for myself. it will copy every list item and remove the 1st coma.
感谢您的提示,我在这里得到了一个工作代码。它将复制每个列表项并删除第一个昏迷。
var list_with_coma = ", " + list_item;
var unwantedCharacter = ",";
$('#id_of_input').val(function(){
if (this.value.charAt(0) == unwantedCharacter){
this.value = this.value.substr(1);}
return this.value + list_with_coma;
});

