unicorn/prefer-string-starts-ends-with 正確性
作用
優先使用 String#startsWith()
和 String#endsWith()
,而不是使用帶有 /^foo/
或 /foo$/
的正規表示式。
為何這不好?
使用 String#startsWith()
和 String#endsWith()
更具可讀性且效能更高,因為它不需要解析正規表示式。
範例
此規則的 不正確 程式碼範例
javascript
const foo = "hello";
/^abc/.test(foo);
此規則的 正確 程式碼範例
javascript
const foo = "hello";
foo.startsWith("abc");