通过 JS 中的 mb_strlen 等字符检查长度

Quy*_*yen 1 javascript

你知道如何在JS中像PHP中的mb_strlen函数一样检查字符长度吗?我刚刚知道使用这种方式,它计算的是字节而不是字符。太感谢了!

$(".textarea").val().length

Tak*_*Isy 5

如果您使用 UTF-8,我想以下函数适合您,
因为它应该替换所有多字节字符,然后获取长度:

function countChars(str) {
  return str.replace(/[\u0080-\u10FFFF]/g, "x").length;
}

console.log(countChars('abc abc abc'));
Run Code Online (Sandbox Code Playgroud)

(文档: https: //en.wikipedia.org/wiki/UTF-8#Description


另一种方法是使用.split('')并获取数组的长度:

function countChars(str) {
  return str.split('').length;
}

console.log(countChars('abc abc abc'));
Run Code Online (Sandbox Code Playgroud)

不管怎样,我希望你能给出字符串的例子来看看它的工作原理!

我希望它有帮助。