Reputation: 2980
I have this requirement where it is required to remove only the last .
dot sign from a string.
Say if we have var str = 'abcd dhfjd.fhfjd.';
i need remove the final dot sign which would output abcd dhfjd.fhfjd
.
I found this link ( Javascript function to remove leading dot ) which removes the first dot sign but I am new to this whole thing and could not find any source on how to remove a specific last character if exists.
Thank you :)
Upvotes: 23
Views: 41751
Reputation: 4176
This will remove all trailing dots, and may be easier to understand for a beginner (compared to the other answers):
while(str.charAt(str.length-1) == '.')
{
str = str.substr(0, str.length-1);
}
Upvotes: 1
Reputation: 10982
Single dot:
if (str[str.length-1] === ".")
str = str.slice(0,-1);
Multiple dots:
while (str[str.length-1] === ".")
str = str.slice(0,-1);
Single dot, regex:
str = str.replace(/\.$/, "");
Multiple dots, regex:
str = str.replace(/\.+$/, "");
Upvotes: 70
Reputation: 3218
if(str.lastIndexOf('.') === (str.length - 1)){
str = str.substring(0, str.length - 1);
}
Upvotes: 4