JS实现HTML实体与字符的相互转换

function stringToEntity(str,radix){
  let arr=str.split('')
  radix=radix||0
  let tmp=arr.map(item=>
`&#${(radix?'x'+item.charCodeAt(0).toString(16):item.charCodeAt(0))};`).join('')
  console.log(`'${str}' 转实体为 '${tmp}'`)
  return tmp
}
function entityToString(entity){
  let entities=entity.split(';')
  entities.pop()
  let tmp=entities.map(item=>String.fromCharCode(
  item[2]==='x'?parseInt(item.slice(3),16):parseInt(item.slice(2)))).join('')
  console.log(`'${entity}' 转字符串为 '${tmp}'`)
  return tmp
}

  

posted @ 2017-07-18 11:22    阅读(2894)  评论(0编辑  收藏  举报