Skip to content

fix[truncate]: escape string separator in RegExp - #2130

Open
TalhaHunter101 wants to merge 1 commit into
toss:mainfrom
TalhaHunter101:fix/compat-truncate-escape-separator
Open

TalhaHunter101 wants to merge 1 commit into
toss:mainfrom
TalhaHunter101:fix/compat-truncate-escape-separator

Conversation

@TalhaHunter101

Copy link
Copy Markdown

Summary

Fixes #2129

When options.separator is a string containing RegExp metacharacters (such as ?, +, *, [, (, ., \), truncate in es-toolkit/compat directly interpolates it into new RegExp without escaping. This causes SyntaxError: Invalid regular expression crashes when the separator contains quantifiers or unclosed brackets, and unintended wildcard behavior for ..

Difference from Lodash

import _ from 'lodash';
import { truncate } from 'es-toolkit/compat';

// Separator with '?'
_.truncate('hello world? how are you doing?', { length: 20, separator: '?' });
// => "hello world..."

truncate('hello world? how are you doing?', { length: 20, separator: '?' });
// => crashes with SyntaxError: Invalid regular expression: /(?<result>.*(?:(?!?).))(?:?)/u: Invalid quantifier

// Separator with '['
truncate('section [1] details and notes', { length: 20, separator: '[' });
// => crashes with SyntaxError: Invalid regular expression: Unterminated character class

With this change, truncate escapes string separators using escapeRegExp, matching Lodash's behavior and preventing regex syntax crashes.

Changes

  • Escaped string separator with escapeRegExp before building the truncation RegExp.
  • Added regression tests in src/compat/string/truncate.spec.ts covering string separators containing RegExp metacharacters (?, [, (, +, *, ., and \).

@vercel

vercel Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
es-toolkit Error Error Oct 1, 2026 10:55pm UTC

Request Review

This branch had an error being deployed

1 failed deployment
Preview — 7b4f6fc0 Deployed Oct 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

compat/truncate: crashes with SyntaxError when string separator contains RegExp metacharacters

1 participant