4

我想验证字符串是否以 JavaScript 中的空格结尾。提前致谢。

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

if (endSpace.test(str)) {
    window.console.error("ends with space");
    return false;
}
4

6 回答 6

6

您可以使用endsWith(). 它会比regex

myStr.endsWith(' ')

endsWith()方法确定一个字符串是否以另一个字符串的字符结尾,返回truefalse酌情。

如果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;
    };
}
于 2015-06-01T06:02:00.907 回答
4

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

于 2015-06-01T05:55:59.937 回答
2
var endSpace = / \s$/;

在上面的行中,您实际上使用了 2 个空格,一个是 ( ),第二个是\s。这就是原因,您的代码无法正常工作。删除其中之一。

var endSpace = / $/; 
var str="hello world "; 
if(endSpace.test(str)) { 
 window.console.error("ends with space"); return false; 
}
于 2015-06-01T05:59:27.927 回答
1

你也可以试试这个:

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

}
于 2015-06-01T06:01:52.987 回答
0

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

if(/\s+$/.test(str)) {
   window.console.error("ends with space");
   return false;
}
于 2015-06-01T05:58:08.563 回答
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>

于 2015-06-01T06:05:09.233 回答