美文网首页
2018-12-18 中文转unicode 符合js规则

2018-12-18 中文转unicode 符合js规则

作者: 流光念岁月 | 来源:发表于2018-12-18 14:24 被阅读0次
 /// <summary>
    /// unicode 转中文(符合js规则)
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UnicodeJsCodeToCN(string str)
    {
        string outStr = "";
        Regex reg = new Regex(@"(?i)%u([0-9a-f]{4})");
        outStr = reg.Replace(str,delegate(Match m)
        {
            return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
        });
        return outStr;
    }
    /// <summary>
    /// 中文转unicode 符合js规则
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UnicodeJsCNToCode(string str)
    {
        string outStr = "";
        if (!string.IsNullOrEmpty(str))
        {
            for(int i=0;i<str.Length;i++)
            {
                if(Regex.IsMatch(str[i].ToString(),@"[\u4e00-\u9fa5]"))
                {
                    outStr += @"%u" + ((int)str[i]).ToString("x");
                }
                else
                {
                    outStr += str[i];
                }
            }
        }
        return outStr;
    }

相关文章

网友评论

      本文标题:2018-12-18 中文转unicode 符合js规则

      本文链接:https://www.haomeiwen.com/subject/jaflkqtx.html