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

use*_*534 4 javascript regex validation jquery ends-with

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

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

if (endSpace.test(str)) {
    window.console.error("ends with space");
    return false;
}
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 6

\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
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)
function test() {
  var endSpace = /\s$/;
  var str = document.getElementById('abc').value;

  if (endSpace.test(str)) {
    window.console.error("ends with space");
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)


Tus*_*har 5

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

myStr.endsWith(' ')
Run Code Online (Sandbox Code Playgroud)

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

如果endsWith不通过浏览器的支持,您可以用填充工具由MDN提供:

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;
    };
}
Run Code Online (Sandbox Code Playgroud)