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

2018-12-18  本文已影响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;
    }
上一篇 下一篇

猜你喜欢

热点阅读