Skip to content

Commit e324c0f

Browse files
fix(compiler): fix how trimSafely handles &nbsp (#70)
* fix(compiler): fix how `trimSafely` handles `&nbsp` * fix: import error
1 parent 9c3dc98 commit e324c0f

3 files changed

Lines changed: 30 additions & 23 deletions

File tree

.changeset/soft-garlics-carry.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@replexica/compiler": patch
3+
---
4+
5+
fix how trimSafely handles &nbsp
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { describe, it, expect } from 'vitest';
2+
import { trimSafely } from './text';
3+
4+
describe('trimSafely', () => {
5+
it('should coalesce leading/trailing spaces', () => {
6+
const input = '\n Hello World \n';
7+
const expected = ' Hello World ';
8+
const actual = trimSafely(input);
9+
10+
expect(actual).toBe(expected);
11+
});
12+
it('should keep leading/trailing NBSPs', () => {
13+
const input = ' \n \u00A0 \u00A0 Hello World \u00A0 \u00A0 \n ';
14+
const expected = ' \u00A0 \u00A0 Hello World \u00A0 \u00A0 ';
15+
const actual = trimSafely(input);
16+
17+
expect(actual).toBe(expected);
18+
});
19+
});
Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,8 @@
1-
export function trimSafely(inputText: string) {
2-
let result = inputText;
3-
4-
const leadingNbspCount = (result.match(/^\u00A0+/) || [''])[0].length;
5-
6-
// Trim start
7-
let resultWithTrimmedStart = result.trimStart();
8-
resultWithTrimmedStart = '\u00A0'.repeat(leadingNbspCount) + resultWithTrimmedStart;
9-
if (resultWithTrimmedStart.length !== result.length) {
10-
resultWithTrimmedStart = ' ' + resultWithTrimmedStart;
11-
}
12-
result = resultWithTrimmedStart;
13-
14-
const trailingNbspCount = (result.match(/\u00A0+$/) || [''])[0].length;
15-
16-
// Trim end
17-
let resultWithTrimmedEnd = result.trimEnd();
18-
resultWithTrimmedEnd = resultWithTrimmedEnd + '\u00A0'.repeat(trailingNbspCount);
19-
if (resultWithTrimmedEnd.length !== result.length) {
20-
resultWithTrimmedEnd = resultWithTrimmedEnd + ' ';
21-
}
22-
result = resultWithTrimmedEnd;
1+
export function trimSafely(input: string): string {
2+
// repleace \n with space
3+
let result = input.replace(/\n/g, ' ');
4+
// remove duplicate spaces, but not the NBSPs
5+
result = result.replace(/ +/g, ' ');
236

247
return result;
25-
}
8+
}

0 commit comments

Comments
 (0)