Skip to content

noUnnecessaryStringTrim (JavaScript)

Language JavaScript (and super languages)
biome.json
{
"linter": {
"rules": {
"nursery": {
"noUnnecessaryStringTrim": "error"
}
}
}
}

Disallow trim() before startsWith() or endsWith() when only one side of the string matters.

startsWith() only looks at the start of a string, so whitespace removed from the end by trim() can’t change its result. The same is true for endsWith() and whitespace at the start. Use trimStart() before startsWith() and trimEnd() before endsWith() to remove only the whitespace that matters.

The rule only reports calls where the searched text is known and the change can’t affect the result. It ignores these calls:

  • startsWith() calls whose searched text ends with whitespace, and endsWith() calls whose searched text starts with whitespace.
  • Calls whose searched text is a variable or expression that the rule can’t work out.
  • Calls with a second argument, which sets the position to search from.
  • Calls that use optional chaining (?.).
value.trim().startsWith("-");
code-block.js:1:7 lint/nursery/noUnnecessaryStringTrim  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ This trim() call removes whitespace from both ends of the string, but startsWith() only needs it removed from the start.

> 1 │ value.trim().startsWith("-");
│ ^^^^^^
2 │

ℹ Whitespace at the end of the string can't change the result of startsWith() here.

ℹ Use trimStart() to remove whitespace from the start only.

ℹ This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

ℹ Unsafe fix: Use trimStart() instead.

1 │ - value.trim().startsWith("-");
1 │ + value.trimStart().startsWith("-");
2 2 │

value.trim().endsWith("-");
code-block.js:1:7 lint/nursery/noUnnecessaryStringTrim  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

ℹ This trim() call removes whitespace from both ends of the string, but endsWith() only needs it removed from the end.

> 1 │ value.trim().endsWith("-");
│ ^^^^^^
2 │

ℹ Whitespace at the start of the string can't change the result of endsWith() here.

ℹ Use trimEnd() to remove whitespace from the end only.

ℹ This rule belongs to the nursery group, which means it is not yet stable and may change in the future. Visit https://biomejs.dev/linter/#nursery for more information.

ℹ Unsafe fix: Use trimEnd() instead.

1 │ - value.trim().endsWith("-");
1 │ + value.trimEnd().endsWith("-");
2 2 │

value.trimStart().startsWith("-");
value.trimEnd().endsWith("-");
value.trim().startsWith("-", 1);
value.trim().startsWith("foo ");
value.trim().endsWith(suffix);