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 :)
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(/\.+$/, "");
if(str.lastIndexOf('.') === (str.length - 1)){
str = str.substring(0, str.length - 1);
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With