JavaScript全角和半角相互转换

快乐打工仔 分类:实例代码

JavaScript全角和半角相互转换属于前端实例代码,有关更多实例代码大家可以查看

下面是javascript实现的全角和半角相互转换代码,需要的朋友可以借鉴一下:

一.半角转换为全角函数:

function ToDBC(str){
  var result = '';
  for(var i=0; i < str.length; i++){
    code = str.charCodeAt(i);
    if(code >= 33 && code <= 126){
      result += String.fromCharCode(str.charCodeAt(i) + 65248);
    }else if (code == 32){
      result += String.fromCharCode(str.charCodeAt(i) + 12288 - 32);
    }else{
      result += str.charAt(i);
    }
  }
  return result;
}

二.全角转换为半角函数:

function ToCDB(str){
  var result = '';
  for(var i=0; i < str.length; i++){
    code = str.charCodeAt(i);
    if(code >= 65281 && code <= 65374){
      result += String.fromCharCode(str.charCodeAt(i) - 65248);
    }else if (code == 12288){
      result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
    }else{
      result += str.charAt(i);
    }
  }
  return result;
}

JavaScript全角和半角相互转换,这样的场景在实际项目中还是用的比较多的,关于JavaScript全角和半角相互转换就介绍到这了。

回复

我来回复
  • 暂无回复内容