Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove dot . sign from the end of the string

Tags:

javascript

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 :)

like image 722
Hasitha Shan Avatar asked Jan 04 '14 18:01

Hasitha Shan


3 Answers

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(/\.+$/, "");
like image 63
cookie monster Avatar answered Nov 13 '22 18:11

cookie monster


if(str.lastIndexOf('.') === (str.length - 1)){
    str = str.substring(0, str.length - 1);
}
like image 36
juminoz Avatar answered Nov 13 '22 17:11

juminoz


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);
}
like image 1
inspector-g Avatar answered Nov 13 '22 18:11

inspector-g