如何在字符串末尾添加句号,除非有问号、感叹号或分号

How to add a full stop to the end of a string, except if there is question mark, exclamation mark or semicolon?

本文关键字:感叹 字符串 添加      更新时间:2024-05-06

这只适用于完全停止:

if (string.charAt(string.length-1) != ".") {
        string = string+".";
};

只需在"if"语句中添加额外条件,即可表示"不是a。或a?或a!或a;

您可以这样使用:

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the first character of a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "HELLO WORLD?";
if(str.charAt(str.length-1) != "." && str.charAt(str.length-1) != "?" && str.charAt(str.length-1) != "!" && str.charAt(str.length-1) != ";")
document.getElementById("demo").innerHTML=str+".";
else
document.getElementById("demo").innerHTML=str;
}
</script>
</body>
</html>

对于一个条件,您可以执行以下操作:

if(!~[".","!","?",";"].indexOf(string[string.length-1])) string+=".";

说明:

波浪号运算符(~):~x等效于-Math.floor(x)-1这意味着如果最后一个字符不是[".","!","?",";"]中的一个,indexOf返回-1,波浪号运算符变为0,当否定时,它给出true(因为它是falsy)!0 == false

string[x]相当于string.charAt(x)

const addPeriodMark = (str) => {
  return str.endsWith(".") ? str : str + ".";
};

使用endWith()作为条件。