今天遇到了一个接口,提交了很多次返回都是返回参数格式不规范,百思不得其解,折腾了很久,最后才发现是Content-Length的长度错误造成的,原来的代码用的直接是url.body.length,但是在body中包含中文的情况下,这个长度是错误的,于是写了一个改进代码,就正常了。
function countChineseCharacters(str) {
const chineseRegex = /[\u4e00-\u9fa5]/g; // 匹配中文字符的正则表达式
const chineseMatches = str.match(chineseRegex); // 获取所有中文字符的数组
const chineseCount = chineseMatches ? chineseMatches.length : 0; // 计算中文字符的数量
const englishCount = str.length - chineseCount; // 计算非中文字符的数量
const totalLength = chineseCount * 3 + englishCount; // 计算总长度
return totalLength;
}