Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first character from a string if it is a comma

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 substr function but this will remove anything regardless of what it is.

My current code is

text.value = newvalue.substr(1);
like image 419
kwhohasamullet Avatar asked Feb 02 '10 08:02

kwhohasamullet


People also ask

How do you remove the first comma from a string?

replace Method. Another way to remove the leading commas from a string is to use the JavaScript string's replace method. We call replace with /^,/ to replace the leading comma with an empty string.

How do I remove the first comma from a string in Java?

You can use the substring() method of java. lang. String class to remove the first or last character of String in Java. The substring() method is overloaded and provides a couple of versions that allows you to remove a character from any position in Java.

How do I remove the first comma from a string in Python?

Remove Commas From String Using the re Package in Python In the re pacakge of Python, we have sub() method, which can also be used to remove the commas from a string. It replaces all the , in the string my_string with "" and removes all the commas in the string my_string .


3 Answers

text.value = newvalue.replace(/^,/, '');

Edit: Tested and true. This is just one way to do it, though.

like image 129
jensgram Avatar answered Oct 14 '22 12:10

jensgram


s = (s.length && s[0] == ',') ? s.slice(1) : s;

Or with a regex:

s = s.replace(/^,/, '');
like image 32
Max Shawabkeh Avatar answered Oct 14 '22 12:10

Max Shawabkeh


var result = (myString[0] == ',') ? myString.substr(1) : myString;
like image 30
Jimmy Avatar answered Oct 14 '22 10:10

Jimmy