javascript 删除点。从字符串的末尾开始签名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20925157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:37:34  来源:igfitidea点击:

Remove dot . sign from the end of the string

javascript

提问by Hasitha Shan

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.

假设我们有 varstr = 'abcd dhfjd.fhfjd.';我需要删除将输出的最后一个点符号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.

我找到了这个链接(删除前导点的 Javascript 函数),它删除了第一个点符号,但我对整个事情很陌生,找不到任何关于如何删除特定最后一个字符(如果存在)的来源。

Thank you :)

谢谢 :)

回答by cookie monster

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(/\.+$/, "");

回答by juminoz

if(str.lastIndexOf('.') === (str.length - 1)){
    str = str.substring(0, str.length - 1);
}

回答by inspector-g

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);
}