【问题标题】:startsWith string method with empty searchString带有空 searchString 的startsWith 字符串方法
【发布时间】:2018-09-09 02:39:09
【问题描述】:

为什么当 searchString 为空时,startsWith 方法返回 true。我认为在其他字符串方法中也是如此,例如包含、endsWith。如果我想避免它,我该怎么办,即如果 searchString 为空,它应该返回 false。

var haystack = 'Hello World!', needle ='';
console.log( haystack.startsWith( needle ) );

【问题讨论】:

标签: javascript string-function


【解决方案1】:

因为它被设计为返回所以。空字符串表示存在 0 个字符。这就是为什么,在某种程度上,每个字符串至少以空白开头。

如果你还想返回false,你可以这样做:

var haystack = 'Hello World!',
  needle = '';
console.log(Boolean(needle) && haystack.startsWith(needle));

首先检查检查器字符串的布尔等效项,如果它为空,则返回值变为false

【讨论】:

  • 你不需要Boolean。空字符串是假的。
  • @Tushar -- 没错,但 console.log 会为该表达式打印空。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
  • 2020-07-09
  • 2012-08-20
相关资源
最近更新 更多