【发布时间】:2019-05-12 00:33:15
【问题描述】:
当我尝试在 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
有没有更好的方法?
【问题讨论】:
标签: javascript string search unicode