JS表情替换代码,这里使用字符取代图片路径
Posted jzdwajue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS表情替换代码,这里使用字符取代图片路径相关的知识,希望对你有一定的参考价值。
需求:将一段字符串中出现的特定字符替换为指定的图片或其他
解决的方法:
<script> var json = ‘[{"title":"微笑","src":14},{"title":"撇嘴","src":2},{"title":"色","src":3},{"title":"发呆","src":4},{"title":"得意","src":5},{"title":"流泪","src":200},{"title":"害羞","src":6},{"title":"闭嘴","src":7},{"title":"睡","src":8},{"title":"大哭","src":9},{"title":"尴尬","src":10},{"title":"发怒","src":11},{"title":"调皮","src":12},{"title":"呲牙","src":13},{"title":"吃惊","src":1},{"title":"难过","src":15},{"title":"酷","src":16},{"title":"冷汗","src":63},{"title":"抓狂","src":17},{"title":"吐","src":18},{"title":"偷笑","src":19},{"title":"可爱","src":20},{"title":"白眼","src":21},{"title":"傲慢","src":22},{"title":"饥饿","src":23},{"title":"困","src":24},{"title":"惊恐","src":25},{"title":"流汗","src":26},{"title":"憨笑","src":27},{"title":"大兵","src":28},{"title":"奋斗","src":29},{"title":"咒骂","src":201},{"title":"疑问","src":30},{"title":"嘘","src":31},{"title":"晕","src":32},{"title":"折磨","src":202},{"title":"衰","src":33},{"title":"骷髅","src":34},{"title":"敲打","src":35},{"title":"再见","src":36},{"title":"察汗","src":203},{"title":"抠鼻","src":64},{"title":"鼓掌","src":65},{"title":"糗大了","src":66},{"title":"坏笑","src":67},{"title":"左哼哼","src":68},{"title":"右哼哼","src":69},{"title":"哈欠","src":70},{"title":"歧视","src":71},{"title":"委屈","src":72},{"title":"快哭了","src":73},{"title":"阴险","src":74},{"title":"亲亲","src":75},{"title":"吓","src":76},{"title":"可怜","src":77},{"title":"菜刀","src":204},{"title":"西瓜","src":62},{"title":"啤酒","src":205},{"title":"篮球","src":206},{"title":"兵乓","src":207},{"title":"咖啡","src":8},{"title":"饭","src":49},{"title":"猪头","src":40},{"title":"玫瑰","src":50},{"title":"凋谢了","src":51},{"title":"示爱","src":208},{"title":"爱心","src":52},{"title":"心碎","src":53},{"title":"蛋糕","src":42},{"title":"闪电","src":43},{"title":"炸弹","src":44},{"title":"刀","src":45}]‘; json = eval(‘(‘+ json +‘)‘); var pattern1 = /\[[\u4e00-\u9fa5]+\]/g; var pattern2 = /\[[\u4e00-\u9fa5]+\]/; var contents = "[微笑]美女[色]你好[害羞]在吗?"; content = contents.match(pattern1); str = contents; for(i=0;i<content.length;i++){ for(j=0;j<json.length;j++){ if("["+ json[j].title +"]" == content[i]){ src = json[j].src; break; } } str = str.replace(pattern2,src); } alert(str); </script>过程: 1、分析JSON字符串中各内容的涵义 2、利用正則表達式找出须要替换的内容 3、利用两次循环,并结合推断将相应内容替换
以上是关于JS表情替换代码,这里使用字符取代图片路径的主要内容,如果未能解决你的问题,请参考以下文章
把一个字符串里符合表情文字标签的地方全部替换为相应的图片的方法
JS 把纯字符串,替换成有链接的图片形式,比如/uploads/101207/1.jpg变成图片显示有链接的也就是HTML代码