如何检查 string.endsWith 并忽略空格

How to check for string.endsWith and ignore whitespace

我有这个工作函数,用于检查字符串是否以 :

结尾
var string = "This is the text:"

function (string) {
  if (string.endsWith(':')) {
    // ends with :
  }
  if (string.endsWith(': ')) {
   // ends with : and a space
  }
  else {
    // does not end with :
  }
}

我还想检查字符串是否以冒号结尾,后跟 space,甚至两个 space::_:__(其中下划线代表 spaces 在这个语法中)。

关于如何在不使用多个 if 语句或定义冒号和 space 的每种可能组合的情况下实现这一点的任何想法?假设冒号后可能有任意数量的 space,但如果最后一个可见字符是冒号,我想在我的函数中捕获它。

您可以使用 String.prototype.trimEnd 删除末尾的空格,然后检查:

function (string) {
  if (string.endsWith(':')) {
    // ends with :
  }
  else if (string.trimEnd().endsWith(':')) {
   // ends with : and white space
  }
  else {
    // does not end with :
  }
}

你好,你可能想使用正则表达式 /(:\s*)/
s* 将匹配 0 或所有空格(如果存在)

对于您的具体示例,@Steve 的回答会很好,因为您正在针对字符串末尾的特定条件进行测试。但是,如果您想针对更复杂的字符串进行测试,您还可以考虑使用 Regular Expressions(也称为 RegEx)。 Mozilla 文档有一个关于如何为 JavaScript.

使用正则表达式的优秀教程

要创建一个正则表达式模式并使用它来测试您的字符串,您可以执行如下操作:

const regex = /:\s*$/;

// All three will output 'true'
console.log(regex.test('foo:'));
console.log(regex.test('foo: '));
console.log(regex.test('foo:  '));

// All three will output 'false'
console.log(regex.test('foo'));
console.log(regex.test(':foo'));
console.log(regex.test(': foo'));

...正则表达式 /:\s*$/ 可以这样解释:

/     Start of regex pattern
 :    Match a literal colon (:)
 \s   Right afterward, match a whitespace character
   *  Match zero or more of the preceding characters (the space character)
 $    Match at the end of the string
/     End of regex pattern

您可以使用 Regexr.com 对您提出的不同正则表达式模式进行实时测试,您可以在文本框中输入示例文本以查看您的模式是否匹配。

正则表达式是一个强大的工具。在某些情况下你想使用它们,而在其他情况下它是多余的。对于您的特定示例,仅使用简单的 .endsWith() 更直接并且很可能是首选。如果您需要在 JavaScript 函数无法解决的情况下进行复杂的模式匹配,正则表达式可以解决问题。值得一读,还有另一个好工具可以放入工具箱。