Skip to content

Instantly share code, notes, and snippets.

@hikariyo
Created December 10, 2022 11:39
Show Gist options
  • Select an option

  • Save hikariyo/b838dff3bdf0d280b25f50a66abd699c to your computer and use it in GitHub Desktop.

Select an option

Save hikariyo/b838dff3bdf0d280b25f50a66abd699c to your computer and use it in GitHub Desktop.
Count both English and Chinese words.
function countWords(str) {
const chinese = Array.from(str)
.filter(ch => /[\u4e00-\u9fa5]/.test(ch))
.length
const english = Array.from(str)
.map(ch => /[a-zA-Z0-9\s]/.test(ch) ? ch : ' ')
.join('').split(/\s+/).filter(s => s)
.length
return chinese + english
}
console.log(countWords('Hello, world, 你好, 世界'))
// 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment