如何检查字符串以javascript中的空格结尾?

时间:2015-06-01 05:54:26

标签: javascript jquery regex validation ends-with

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

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

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

6 个答案:

答案 0 :(得分:3)

\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>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

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

答案 2 :(得分:1)

你也可以试试这个:

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

}

答案 3 :(得分:0)

您可以使用以下代码段 -

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

答案 4 :(得分:0)

var endSpace = / \s$/;

在上面一行中,您实际上使用了两个空格,一个是(),第二个是\s。这就是原因,你的代码不起作用。删除其中一个。

var endSpace = / $/; 
var str="hello world "; 
if(endSpace.test(str)) { 
 window.console.error("ends with space"); return false; 
}

答案 5 :(得分:0)

&#13;
&#13;
$(document).ready(function() {
  $("#butCheck").click(function() {
    var checkString = $("#phrase").val();
    if (checkString.endsWith(' ')) {
      $("#result").text("space");
    } else {
      $("#result").text("no space");
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

相关问题