背景:收到需求,在用户输入emoji表情后,由于后端未做特殊字符限制,则会导致错误,所以在前端过滤掉emoji字符,可以使用 JavaScript 的正则表达式来过滤掉emoji 字符
<template>
<div>
<label>输入框:</label>
<input type="text" v-model="inputValue" @input="handleInput" placeholder="不允许输入 Emoji">
<p>当前值:{{ inputValue }}</p>
</div>
</template>
<script>
export default {
data() {
return {
inputValue: ''
};
},
methods: {
handleInput() {
this.inputValue = this.removeEmoji(this.inputValue);
},
removeEmoji(text) {
return text.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, '');
}
}
};
</script>
实现思路:在上述示例中,我们添加了一个名为 removeEmoji
的辅助函数,用于从文本中删除 Emoji 字符。该函数使用正则表达式 /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
来匹配 Unicode 表示形式的 Emoji 字符,然后将其替换为空字符串。
控制台运行结果:
请注意,由于 Emoji 字符的范围广泛且可能随时间变化,无法保证完全过滤所有的 Emoji 字符。因此,如果需要更严格的过滤或更全面的 Emoji 支持,可能需要使用专门的 Emoji 过滤库或更复杂的验证逻辑。