JS字符串中文转UTF编码

function _uniencode(str){
  str = str || ''
  var newStr = ''
  for (var i = 0,len = str.length;i < len ; i++ ) {
    console.log(str[i])
    console.log(str[i].charCodeAt())
    if(str[i].charCodeAt() > 256) {
      // var strH = str[i].charCodeAt().toString(16)
      var strH = str[i].charCodeAt().toString(16)
      console.log(strH)  // 6211
      str[i] = '%u' + strH  // '%u' + 6211
      console.log('%u' + strH) //%u6211
      console.log(str[i]) //  我
      newStr += '%u' + strH
    } else {
      newStr += str[i]
    }
  }
  console.log(newStr)
  return newStr
}
_uniencode('str  wo我12')

实现字符串中code大于256的用UTF转码功能。复制代码