如何检测div中的大多数字符是阿拉伯语还是拉丁语?



我想将方向属性 RTL/LTR 添加到 DIV 或段落 HTML 标签中,具体取决于最多的字符数,无论是阿拉伯语还是拉丁字符。

我正在尝试通过JavaScript来做到这一点,并通过正则表达式寻找字符。

我在 GitHub 上找到了这个 https://github.com/miladd3/automatic-direction/blob/master/automatic-direction.js 这将完全按照我的意愿进行,但它仅适用于输入表单。

我不懂 JS,我不知道如何使用 GitHub 中的相同代码来计算 HTML 标签中的字符并添加 RTL/LTR 属性。

任何帮助将不胜感激。

为了使该脚本适用于具有.dir-auto类的所有元素,您可以像这样更改它:

window.addEventListener('load', function() {
var elements = [].slice.call(document.querySelectorAll('.dir-auto'));
elements.forEach(function(el) {
var text = el.innerText,
farsiChars = text.match(/[u0600-u06FF]/g),
spaceChars = text.match(/s/g),
count = text.length,
farsiCount = farsiChars ? farsiChars.length : 0
spaceCount = spaceChars ? spaceChars.length : 0,
latinCount = count - farsiCount - spaceCount;
el.setAttribute('dir', (farsiCount > latinCount) ? 'rtl' : 'ltr');
});
});

最新更新