繁体   English   中英

如何检查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 :
  }
}

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

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

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

对于您的特定示例,@ Steve的答案将很好地起作用,因为您正在针对字符串末尾的特定条件进行测试。 但是,如果要针对更复杂的字符串进行测试,则还可以考虑使用正则表达式 (也称为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函数不会削减它,则正则表达式可以解决问题。 值得一读,并在工具箱中放置另一个好工具。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM