sathish kumar
sathish kumar

Reputation: 1197

removing a comma or semicolon from the end of a string if present -using javascript

I am getting a comma seperated or semicolon seperated string. I want to remove the comma or the semicolon which may occur at the end of the string.

e.g.a,b,c, should be converted to a,b,c

a;b;c; should be converted to a;b;c

I want a javascript or regex expression which removes the comma (,) or the semi colon (;) only if it occurs otherwise the string should be left as it is.

please help

Upvotes: 3

Views: 22837

Answers (5)

Treffynnon
Treffynnon

Reputation: 21563

Solution

This can be solved simply with regex MDN DOCs and .replace() MDN DOCs:

your_string = your_string.replace(/[,;]$/,'');

Here is a jsfiddle that you can run to demo the code: http://jsfiddle.net/5eksE/1/

What's happening

/[,;]$/ is the regex portion of this script. The slashes can be ignored as they are just regex delimiters.

[] is a container for a range of values that you would like to match in this case ,;.

$ indicates the end of the string.

So putting it all together we are hunting for the comma or semi-colon that is right at the end of a string.

Upvotes: 18

octern
octern

Reputation: 4868

treffynnon's answer is correct. To elaborate a little, it just checks whether your string matches the regular expression ,$ (where $ indicates the end of the string), and if so, replaces the comma with an empty string. If you wanted to check for either a comma or a semicolon, you would just change it to

your_string = your_string.replace(/[,;]$/,'');

Upvotes: 1

valanto
valanto

Reputation: 921

Regex to handle both comma and semicolon

your_string = your_string.replace(/[,;]$/, "");

Upvotes: 4

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23094

You can check where a character occurs in a string using indexOf() and lastIndexOf(). In your case, when lastIndexOf() returns an index that is equal to the length of string minus 1, then the index is for the last character in the string:

var index = input.lastIndexOf(";");
if(index == input.length - 1) 
{
  input = input.substring(0, input.length - 1);
}

Or, as a one liner:

input = input.lastIndexOf(";") == input.length - 1 ?  input.substring(0, input.length -1 ) : input;

Upvotes: 3

avanderw
avanderw

Reputation: 675

I normally do

value = value.substring(0, value.length-1)

although I ensure that it is there in my previous loop. Sorry missed the second part of your question. You could put in a ternery

value = value.substring(0, (value[value.length-1] == ',') ? value.length -1 : value.length);

although it is not that elegant.

Upvotes: 0

Related Questions