我想在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$/;
),另一个是 \s
。这就是为什么您的代码无法正常工作的原因。请删除其中一个空格。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+|\s+$/g).test(value);
John R
匹配但John Ron
不匹配。 - Si8/\s.$/
。仅允许字母在末尾/\s[a-z]$/i
。 - Tushar