let str = `"这是我们Docs团队的JavaScript总结\\nTypeScript是非常棒的语言"`;
console.log(str)
let cursorIndex = 0;
function isCn(str) {
var reg = new RegExp("[\\\\u4E00-\\\\u9FFF]+", "g");
if (reg.test(str)) {
return true;
}
}
function isEn(str) {
if (/[A-Za-z]+/g.test(str)) {
return true;
}
}
function insertStr(source, start, newStr) {
return source.slice(0, start) + newStr + source.slice(start);
}
while (cursorIndex < str.length) {
let prevStr = str.charAt(cursorIndex);
let curStr = str.charAt(cursorIndex + 1);
if (isEn(prevStr) && isCn(curStr)) {
str = insertStr(str, cursorIndex + 1, ' ');
cursorIndex = cursorIndex + 2;
} else if (isCn(prevStr) && isEn(curStr)) {
str = insertStr(str, cursorIndex + 1, ' ');
cursorIndex = cursorIndex + 2;
} else {
cursorIndex++;
}
}
console.log(`-------- 中英文排版优化后 ---------`)
console.log(str)