Skip to content

Commit b18ddd1

Browse files
Add character count support for countType: "words" using Intl.Segmenter
Unless the (deprecated) `maxwords` option is used
1 parent 4848496 commit b18ddd1

1 file changed

Lines changed: 15 additions & 3 deletions

File tree

packages/govuk-frontend/src/govuk/components/character-count/character-count.mjs

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -392,10 +392,22 @@ export class CharacterCount extends ConfigurableComponent {
392392
return
393393
}
394394

395-
// Count consecutive non-whitespace results
395+
// Count words
396+
//
397+
// If the (deprecated) `maxwords` option is set, count consecutive
398+
// non-whitespace results rather than using the segmenter
396399
if (this.config.countType === 'words') {
397-
const tokens = text.match(/\S+/g) ?? []
398-
this.count = tokens.length
400+
if (this.config.maxwords !== undefined) {
401+
this.count = text.match(/\S+/g)?.length ?? 0
402+
return
403+
}
404+
405+
const segments = this.segmenter
406+
? Array.from(this.segmenter.segment(text))
407+
: []
408+
409+
// Filter out punctuation and whitespace, leaving only words
410+
this.count = segments.filter((segment) => segment.isWordLike).length
399411
return
400412
}
401413

0 commit comments

Comments
 (0)