项目中有个需要将文字表情替换成图片的需求.
例如: [微笑] >>> 😀
本想着只是替换一下文字, 很简单
结果做的时候发现, 还是有不少问题的:
1) 字符串的replace()函数不能直接全局替换变量, 需要先定义一个正则
let str = aaa;
let name = a;
let regExp = new RegExp(name, 'g');
console.log(str.replace(regExp, 'b')); // bbb
2) 写正则的时候又发现了新问题:需要替换的变量不能包含 [ ] 这类特殊符号
否则会变成这样...
let str = '[微笑]';
let name = '[微笑]';
let newName = '😀';
let regExp = new RegExp(name, 'g');
console.log(str.replace(regExp, newName)); // [😀😀]
3) 特殊符号需要在正则表达式里转义一下, 然后又发现变量里面不能直接写反斜杠\...
let name = "\[aaa]";
console.log(name); // [aaa]
// 需要输入双斜杠才行
let name2 = "\\aaa";
console.log(name2); // \[aaa]
4) 最后得出解决方案..
let str = '[微笑]';
let name = '[微笑]';
let name2 = '\\[微笑\\]';
let newName = '😀';
let regExp = new RegExp(name, 'g');
let regExp2 = new RegExp(name2, 'g');
console.log(str.replace(regExp, newName)); // [😀😀]
console.log(str.replace(regExp2, newName)); // 😀
困惑了很久终于解决了。。
仔细一看并不复杂
写个文章希望能帮到和我一样遇到这种问题的人吧