如何在javascript中检测宽字符?



我为包含中文字符的自定义查询语言编写了一个小型解析器。当检测到语法错误时,它输出如下错误消息:

語法錯誤:應為數,但為字串。
索引 = '3213茂訊'"
^

最后一行只有一个'^'字符来表示错误标记的位置。对于汉字的视觉长度占用了另外两个字符,我需要检测宽字符来计算"^"的位置,以指示正确的标记。有人知道一些函数可以检测javascript中的宽字符吗?

我不确定我是否理解正确。但是您可能想要尝试https://www.npmjs.com/package/wcwidth包。可实现如下:

import wcwidth from 'wcwidth';
const getCharAtPosition = (str, position) => {
let currPos = 0;
return [...str].find(char => {
const charWidth = wcwidth(char);
const isPosition =
currPos === position || (charWidth === 2 && currPos === position - 1);
currPos += charWidth;
return isPosition;
});
};
const indicatorPos = '       ^'.indexOf('^');
console.log(getCharAtPosition(`索引 = '3213茂訊'"`, indicatorPos));
// will log: '

我没有测试它,但是像这样的东西可能有效。

最新更新