javascript - Javascript - 在 unicode 字符串中搜索 unicode 字符串
问题描述
当我尝试在 unicode 字符串中搜索 unicode 字符串时,我找不到解决方案。
例如:检查字符串'vie'
是否包含在字符串中'Mr. ViỆt has a blue house'
所以我尝试如下:
// Convert string to Unicode
function toUnicode(theString) {
var unicodeString = '';
for (var i=0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return unicodeString;
}
// Convert string to be Regex Unicode
function toRegexUnicode(theString) {
var unicodeString = '';
for (var i=0; i < theString.length; i++) {
var theUnicode = theString.charCodeAt(i).toString(16).toUpperCase();
while (theUnicode.length < 4) {
theUnicode = '0' + theUnicode;
}
theUnicode = '\\u' + theUnicode;
unicodeString += theUnicode;
}
return new RegExp('[' + unicodeString + ']')
}
// Search
function searchUnicode() {
var strOriginal = "Mr. ViỆt has a blue house"
var regexUnicode = toRegexUnicode(strOriginal)
var strSearch = toUnicode('vie')
var result = regexUnicode.test(strSearch)
console.log(result)
}
测试地址:https ://www.w3schools.com/code/tryit.asp?filename=FY3NGXMQRMLA
有没有更好的方法?
解决方案
首先,您的正则表达式是错误的。取下大括号。
其次,您正在以错误的方式创建正则表达式测试。您当前正在使用完整字符串设置正则表达式搜索。您也没有将您的转换strOriginal
为 Unicode。这意味着您的searchUnicode
函数需要如下所示:
var strOriginal = "Mr. ViỆt has a blue house"
var strOriginalUnicode = toUnicode(strOriginal)
var strSearch = toUnicode('vie')
var regexUnicode = toRegexUnicode(strSearch)
var result = regexUnicode.test(strOriginalUnicode)
接下来,我们可以toRegexUnicode
这样简化您的功能:
// Convert string to be Regex Unicode
function toRegexUnicode(theString) {
theString = theString.replace(/\\/g, "\\\\")
return new RegExp(theString)
}
无需重复使用您的转换方法。您还将注意到所有\
的全局替换成为\\
。这是因为 Regex 将反斜杠视为转义字符,因此我们需要转义转义字符。
推荐阅读
- node.js - Deploy Azure Function with an Alpine - Unhandled 'error' event
- python-3.x - Unable to update PostgrSQL table using psycopg2
- php - Wordpress 403 禁止错误仅适用于特定菜单
- python - 如何从 Python 中的特定字母输出字符串的其余部分?
- c++ - 在 C++ 中的非托管可执行文件中运行托管可执行文件
- python - Alembic env.py 不读取 Flask 项目中的环境变量
- r - 导出为 pdf 时,ggsave 会更改图形
- dotnetnuke - Timelinejs, 2sxc 更改字体和语言
- reactjs - 与 GCP HTTP 端点反应
- kubernetes - 如何在 WSL 中访问 Kubernetes 集群节点