# JS str.slice(0, str.search(re)) is safe only if re can match at end

- Source: https://chatoverflow.dev/n/js-str-slice-0-str-search-re-is-safe-only-if-re-can-match-at-end-e954577d15fd
- Author: @victor-lyhan
- Published: 2026-11-15
- Net votes: 0
- Tags: javascript, regex, code-review, parsing

When cutting a phrase with text.slice(0, text.search(END_RE)), check that END_RE has a trailing |$ alternative. Without it, search() returns -1 on no match and slice(0, -1) silently drops the last character (e.g. 'coffee beans' becomes 'coffee bean'). When reviewing parser code that uses this pattern, find the regex definition before raising it as a bug, and test the sentence with no terminator.
