如何检查javascript中以空格结尾的字符串
how to check the string ends with space in javascript?
我想验证字符串是否以JavaScript中的空格结尾。提前谢谢。
var endSpace = / 's$/;
var str = "hello world ";
if (endSpace.test(str)) {
window.console.error("ends with space");
return false;
}
您可以使用endsWith()
。它将比regex
:更快
myStr.endsWith(' ')
endsWith()
方法确定一个字符串是否以另一个字符串的字符结尾,并酌情返回true
或false
。
如果浏览器不支持endsWith
,可以使用MDN:提供的polyfill
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
's
表示一个空格,不需要在正则表达式中添加[space]
var endSpace = /'s$/;
var str = "hello world ";
if (endSpace.test(str)) {
window.console.error("ends with space");
//return false; //commented since snippet is throwing an error
}
function test() {
var endSpace = /'s$/;
var str = document.getElementById('abc').value;
if (endSpace.test(str)) {
window.console.error("ends with space");
return false;
}
}
<input id="abc" />
<button onclick="test()">test</button>
var endSpace = / 's$/;
在上面的行中,您实际上使用了两个空格,一个是((,第二个是CCD_10。这就是为什么,您的代码不起作用。取下其中一个。
var endSpace = / $/;
var str="hello world ";
if(endSpace.test(str)) {
window.console.error("ends with space"); return false;
}
您可以使用以下代码片段-
if(/'s+$/.test(str)) {
window.console.error("ends with space");
return false;
}
你也可以试试这个:
var str="hello world ";
var a=str.slice(-1);
if(a==" ") {
console.log("ends with space");
}
$(document).ready(function() {
$("#butCheck").click(function() {
var checkString = $("#phrase").val();
if (checkString.endsWith(' ')) {
$("#result").text("space");
} else {
$("#result").text("no space");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="phrase"></input>
<input type="button" value="Check This" id="butCheck"></input>
<div id="result"></div>
试试这个,它将有助于在字符串中开始和结束空白。
let begin_space_exp = /^'s/;
let end_space_exp = /'s$/;
/* Check for white space */
if (begin_space_exp.test(value) || end_space_exp.test(value)) {
return false;
}`
我发现/^''s+$/有"与";像这样的条件begin_space_exp.test(值(&;end_space_exp.test(值(那么两者都应该是真的。
否则你可以使用
(/^'s+|'s+$/g).test(value);
相关文章:
- 我如何找到一个句子中的所有空格并替换忽略它们
- Regex代码只允许一个空格
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- 拆分文本以每隔n个字符添加一行新行,并注意空格
- 用空格替换下划线PHP
- 如何为jQuery屏蔽输入插件创建一个允许字母数字、空格和重音字符的掩码
- 当没有文本输入聚焦时检测空格键按下
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 一个密码测试程序,如果存在空格,它会提醒用户
- 在谷歌应用程序脚本中转换为空格的制表符
- 匹配由单个空格分隔的单词,单词的开头或结尾不能有空格
- 如何编写RegExpression For在javascript中不允许在字符串中使用前导和结尾空格
- 正则表达式 - 字符串不能以空格开头,以空格结尾,并且连续包含几个空格
- 如何删除正则表达式开头和结尾的空格
- 如何检查字符串是否有空格或结尾
- 如何在文本框的开头和结尾修剪空格
- 如何用正则表达式替换字符串的所有部分,正则表达式以开头,以或空格或{结尾
- 如何生成不包含任何空格的正则表达式,甚至在字符串的开头或结尾也不包含空格
- 确保输入的名称不以空格结尾
- 如何检查javascript中以空格结尾的字符串