【问题标题】:How to detect if string contains Amharic language in javascript?如何在javascript中检测字符串是否包含阿姆哈拉语?
【发布时间】:2019-01-27 10:20:13
【问题描述】:

我需要检查一个字符串是否包含阿姆哈拉语,它也可以包含英文字符:

const amharic = "የሙከራ test ሕብረቁምፊ";
amharc.match(pattern)

【问题讨论】:

标签: javascript regex unicode unicode-string


【解决方案1】:

使用UTF-16 范围和charCodeAt() 方法:

阿姆哈拉字母的UTF-16 范围是从 46085017 以及从 1164811743因此您可以使用charCodeAt() 方法检查字符串字符是否在这两个范围内。


检查并运行以下 代码片段,以获得我上面描述的实际示例:

var string = "የሙከራ test ሕብረቁምፊ";

function checkAmharic(x) {
    let flag = false;   
    [...x].forEach((e, i) => {
    	if (((e.charCodeAt(i) > 4607) && (e.charCodeAt(i) < 5018)) || ((e.charCodeAt(i) > 11647) && (e.charCodeAt(i) < 11743))) {
      	if (flag == false) {
        	flag = true;
        }
      }
    })
    return flag; 
}

console.log(checkAmharic(string)); // will return true
console.log(checkAmharic("Hello All!!")); // will return false

使用ASCII 范围和正则表达式:

阿姆哈拉语字母的ASCII 范围是从1200137F,因此您可以使用正则表达式检查字符串字符是否在这两个范围内。


检查并运行以下 代码片段,以获得我上面描述的实际示例:

var string = "የሙከራ test ሕብረቁምፊ";

function checkAmharic(x) {
    return /[\u1200-\u137F]/.test(x); // will return true if an amharic letter is present
}

console.log(checkAmharic(string)); // will return true
console.log(checkAmharic("A")); // will return false

【讨论】:

  • 如果找到 ascii 'A',测试是否返回 TRUE?
  • @sln 不,它返回 false。我已经更新了答案,包括测试一个带有“A”的字符串来显示这一点。我还添加了另一种 JavaScript 方法,它使用 UTF-16 代替检查字符串中的 amharic 字母。干杯。
猜你喜欢
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 2017-12-16
  • 2010-12-19
相关资源
最近更新 更多