gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:36:51 25 4
gpt4 key购买 nike

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

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

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

最佳答案

您可以使用 endsWith() .它将比 regex 更快:

myStr.endsWith(' ')

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

如果浏览器不支持endsWith,你可以使用polyfill由 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;
};
}

关于javascript - 如何检查javascript中以空格结尾的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30566464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com