如何在字符串末尾添加句号,除非有问号、感叹号或分号
How to add a full stop to the end of a string, except if there is question mark, exclamation mark or semicolon?
这只适用于完全停止:
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()作为条件。
相关文章:
- 如何在JavaScript中将字符串转换为函数引用
- jQuery中是否内置了任何字符串格式化函数
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- ng打开空字符串
- 正则表达式在字符串中找到base64
- 如何将字符串值从php页面发送到java脚本页面
- 子字符串/正则表达式以获取字符串中保存的 SRC 值
- 字符串在将其传递给另一个活动Android JavaScript时读取Null
- 对id以某个字符串开头的元素进行计数
- Javascript逻辑运算符和字符串/数字
- 反向字符串比较
- 如何有效地将游戏数据存储在URL查询字符串中
- 可变大小的JavaScript字符串如何成为基元类型
- 将DOM节点值与字符串Javascript进行比较
- 如何在 Javascript 中将变量的值从字符串转换为整数
- 本地存储中的字符串到字节数组转换
- JavaScript按钮/输入/函数,字符串反转
- 从查询字符串参数推断出正确的数据类型
- 高亮显示与数组字符串一起使用时文本插件中断
- 如何检查字符串的一部分与数组匹配