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

how to check the string ends with space in javascript?

本文关键字:空格 结尾 字符串 javascript 何检查 检查      更新时间:2023-09-26

我想验证字符串是否以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()方法确定一个字符串是否以另一个字符串的字符结尾,并酌情返回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;
    };
}

'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$/;

在上面的行中,您实际上使用了两个空格,一个是((,第二个是CCD_10。这就是为什么,您的代码不起作用。取下其中一个。

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+$/有"与";像这样的条件begin_space_exp.test(值(&amp;end_space_exp.test(值(那么两者都应该是真的。

否则你可以使用

(/^'s+|'s+$/g).test(value);