小编典典

React Javascript显示/解码Unicode字符

reactjs

我有一个需要转换的Unicode字符串。我需要使用\ u00f3将字符串呈现为ó。这是一个示例,它应该与所有其他类型的字符á,í,ú…一起发生

我有以下基本代码:https :
//jsfiddle.net/dddf7o70/

我需要转换

<Hello name="Informaci\u00f3n" />

进入

Información

阅读 803

收藏
2020-07-22

共1个答案

小编典典

如果由于某种原因必须使用其中包含这些\u....代码而不是真实字母的字符串,请将其转换为数字,然后使用String.fromCharCode()将这些数字转换为真实字母。我们可以为此使用正则表达式替换为处理函数:

function convertUnicode(input) {
  return input.replace(/\\u(\w\w\w\w)/g,function(a,b) {
    var charcode = parseInt(b,16);
    return String.fromCharCode(charcode);
  });
}

var Hello = React.createClass({
  getInitialState: function() {
    return {
      name: convertUnicode(this.props.name)
    };
  },
  render: function() {
    return <div>Hello {this.state.name}</div>;
  }
});

React.render(
  <Hello name="Informaci\u00f3n" />,
  document.getElementById('container')
);

小提琴:https :
//jsfiddle.net/dddf7o70/4/

2020-07-22