如何在JavaScript中检查字符串是否以空格结尾?

5

我想在JavaScript中验证字符串是否以空格结尾。谢谢。

var endSpace = / \s$/;
var str = "hello world ";

if (endSpace.test(str)) {
    window.console.error("ends with space");
    return false;
}
7个回答

6
你可以使用 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;
    };
}

如果我想检查一个字符串是否以空格和一个字符结尾,该怎么办?例如:John R 匹配但 John Ron 不匹配。 - Si8
@Si8 使用正则表达式。/\s.$/。仅允许字母在末尾 /\s[a-z]$/i - Tushar

5

\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>


2
var endSpace = / \s$/;

在上面的代码行中,您实际上使用了两个空格,一个是 (),另一个是 \s。这就是为什么您的代码无法正常工作的原因。请删除其中一个空格。
var endSpace = / $/; 
var str="hello world "; 
if(endSpace.test(str)) { 
 window.console.error("ends with space"); return false; 
}

1
您可以使用以下代码片段 -

if(/\s+$/.test(str)) {
   window.console.error("ends with space");
   return false;
}

1
你也可以尝试这个:

var str="hello world ";
var a=str.slice(-1);
if(a==" ") {
        console.log("ends with space");

}

0

$(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>


0

尝试这个,它将帮助在字符串中开始和结束空格。

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+$/ 像这样有一个“AND”条件 begin_space_exp.test(value) && end_space_exp.test(value) 那么两者都应该是真的。
否则,您可以使用
(/^\s+|\s+$/g).test(value);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接