2 回答
TA贡献1856条经验 获得超5个赞
我会通过获取键,转义所有特殊字符并加入|. 然后通过在对象上查找匹配的字符串来替换:
const escape = s => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const replaceStringWithEmoji = (string) => {
const emojiMap = {
':)': '😊',
':(': '🙁',
':D': '😁',
';(': '😥',
':O': '😮',
';)': '😉',
'8)': '😎',
'>:@': '😡',
};
const pattern = new RegExp(
Object.keys(emojiMap).map(escape).join('|'),
'g'
);
return string.replace(pattern, match => emojiMap[match]);
};
console.log(replaceStringWithEmoji('foo :) bar'));
console.log(replaceStringWithEmoji('foo :) bar 8) baz'));
TA贡献1811条经验 获得超5个赞
您不需要将 emojiMap 更改为数组,您可以使用交替构建正则表达式并使用 repalce
const replaceStringWithEmoji = (string) => {
const emojiMap = {
':)': '😊',
':(': '🙁',
':D': '😁',
';(': '😥',
':O': '😮',
';)': '😉',
'8)': '😎',
'>:@': '😡',
};
let regex = /(?::\)|:\(|:D|;\(|:O'|;\)|8\)|>:@)/g
return string.replace(regex,(m)=>emojiMap[m] || m)
};
console.log(replaceStringWithEmoji("Hello :) my name is Alex"))
添加回答
举报
