Skip to content

Commit 29c44bf

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

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -487,13 +487,25 @@ export class CharacterCount extends ConfigurableComponent {
487487
},
488488

489489
/**
490-
* Count consecutive non-whitespace results
490+
* Count words
491+
*
492+
* If the (deprecated) `maxwords` option is set, count consecutive
493+
* non-whitespace results rather than using the segmenter
491494
*
492495
* @param {string} text - Textarea value
493496
* @returns {number} Count
494497
*/
495498
words(text) {
496-
return text.match(/\S+/g)?.length ?? 0
499+
if (this.config.maxwords !== undefined) {
500+
return text.match(/\S+/g)?.length ?? 0
501+
}
502+
503+
const segments = this.segmenter
504+
? Array.from(this.segmenter.segment(text))
505+
: []
506+
507+
// Filter out punctuation and whitespace, leaving only words
508+
return segments.filter((segment) => segment.isWordLike).length
497509
}
498510
})
499511

0 commit comments

Comments
 (0)