Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/compat/string/truncate.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,4 +121,15 @@ describe('truncate', () => {
it('should return base string with omission when separator is not found in truncated string', () => {
expect(truncate('hello world test', { length: 10, separator: 'xyz' })).toEqual('hello w...');
});

it('should support string separators containing RegExp special characters', () => {
expect(truncate('hello world? how are you doing?', { length: 20, separator: '?' })).toBe('hello world...');
expect(truncate('section [1] details and notes', { length: 20, separator: '[' })).toBe('section ...');
expect(truncate('part (A) overview notes', { length: 20, separator: '(' })).toBe('part ...');
expect(truncate('a + b + c + d + e', { length: 12, separator: '+' })).toBe('a + b ...');
expect(truncate('one*two*three*four', { length: 12, separator: '*' })).toBe('one*two...');
expect(truncate('hello.world.foo.bar', { length: 15, separator: '.' })).toBe('hello.world...');
expect(truncate('hello world foo bar', { length: 15, separator: '.' })).toBe('hello world ...');
expect(truncate('path\\to\\nested\\file', { length: 15, separator: '\\' })).toBe('path\\to...');
});
});
3 changes: 2 additions & 1 deletion src/compat/string/truncate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { escapeRegExp } from '../../string/escapeRegExp.ts';
import { regexMultiByte } from '../_internal/regexMultiByte.ts';
import { isObject } from '../predicate/isObject.ts';

Expand Down Expand Up @@ -81,7 +82,7 @@ export function truncate(string?: string, options?: TruncateOptions): string {
}

// Further truncate the string to the last separator using unicode regex
const search = separator instanceof RegExp ? separator.source : separator;
const search = separator instanceof RegExp ? separator.source : escapeRegExp(separator);
const flags = 'u' + (separator instanceof RegExp ? separator.flags.replace('u', '') : '');
const withoutSeparator = new RegExp(`(?<result>.*(?:(?!${search}).))(?:${search})`, flags).exec(base);

Expand Down
Loading