JavaScript 中如何计算字符串长度?

5,808 阅读1分钟

使用 length 属性

JavaScript 中有很多不同的方法计算字符,最常用的方法是使用字符串通用的.length属性,它会返回字符串长度,包括空格和其他不可见字符。

const str = 'Hello,world!'
console.log(str.length) // 12

使用 trim 计算非空字符

如果你只想要计算计算非空格的字符,可以使用.trim()。这会移除字符串开头和结尾的空格。

const str = '   Hello world!  '
console.log(str.trim().length) //12

使用正则表达式

另一种方法是使用正则表达式,这种方法更加通用,因为你可以指定你想要计算的字符。 例如,你可以使用正则表达式只计算字母和数字,或者排除某些字符。

const str = 'Hello, world123!'
const regex = /[a-zA-Z0-9]/g //只计算字母和数字
console.log(str.match(regex).length) //13
const str = 'Hello, world123!'
const regex = /[a-z]/gi //只计算字母
console.log(str.match(regex)?.length)

其他

除了以上方法,还可以使用forEach,for循环,for...in等方法。

How to count characters in JavaScript - Explanation with example code