【问题标题】:How to check for string.endsWith and ignore whitespace如何检查 string.endsWith 并忽略空格
【发布时间】:2018-05-25 19:04:38
【问题描述】:

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

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 :
  }
}

我还想检查字符串是否以冒号后跟空格,甚至两个空格结尾::_:__(其中下划线表示此语法中的空格)。

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

【问题讨论】:

  • 您可能想了解 RegEx。

标签: javascript ends-with


【解决方案1】:

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

【讨论】:

  • 在 Python 3.9 中:AttributeError: 'str' object has no attribute 'trimEnd'
  • 嗨@Timo,这个问题是针对JavaScript的。而不是trimEnd,似乎您可以将rstrip 用于Python。见stackoverflow.com/a/2372578/6184972
【解决方案2】:

对于您的具体示例,@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 函数无法解决的情况下进行复杂的模式匹配,正则表达式可以解决问题。值得一读,并且是另一个放入工具箱的好工具。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多