首页 > 解决方案 > 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

有没有更好的方法?

标签: javascriptstringsearchunicode

解决方案


首先,您的正则表达式是错误的。取下大括号。

其次,您正在以错误的方式创建正则表达式测试。您当前正在使用完整字符串设置正则表达式搜索。您也没有将您的转换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 将反斜杠视为转义字符,因此我们需要转义转义字符。


推荐阅读