我想验证字符串是否以 JavaScript 中的空格结尾。提前致谢。
var endSpace = / \s$/;
var str = "hello world ";
if (endSpace.test(str)) {
window.console.error("ends with space");
return false;
}
我想验证字符串是否以 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$/;
在上面的行中,您实际上使用了 2 个空格,一个是 ( ),第二个是
\s
。这就是原因,您的代码无法正常工作。删除其中之一。
var endSpace = / $/;
var str="hello world ";
if(endSpace.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");
}
您可以使用以下代码片段 -
if(/\s+$/.test(str)) {
window.console.error("ends with space");
return false;
}
$(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>