【问题标题】:Converting string to emoji将字符串转换为表情符号
【发布时间】:2021-10-04 12:33:34
【问题描述】:

我有以下函数用给定的表情符号替换字符串代码。

export const CHARS = {
  ":)": "????",
  "(:": "????",
  ":-)": "????",
  ":(": "????",
  "):": "????",
  ":-(": "????",
  ":/": "????",
}

convertEmoji = string => {
    const escape = s => s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")
    const pattern = new RegExp(
      Object.keys(CHARS).map(escape).join("|"),
      "g"
    )
    return string.replace(pattern, match => CHARS[match])
}

这按预期工作,但当任何给定的 CHARS[key] 出现在单词中时,它也会转换。

例如,将此函数传递给包含 URL 的字符串:

https://google.com

变成:

https????/google.com

我希望仅当表情符号代码在给定句子中显示为单词时才可以使用替换功能。例如:

:) Hello world! - 函数在这里应该可以工作。

:)Hello world! - 在这里它不应该工作,因为表情符号代码没有正确的空格。

请帮我解决这个问题。

【问题讨论】:

  • 为什么您首先会将https://google.com 传递给convertEmoji
  • 如果之前或之后有某些字符,您可以添加否定环视以防止匹配。
  • @h0r53 大概是用户聊天输入,他们可能会输入一个 URL。

标签: javascript regex replace emoji


【解决方案1】:

您需要为您的模式指定左侧和右侧的上下文。

如果您想确保左右两侧没有立即出现单词字符,则需要用(?<!\w)(?!\w) 环视来表达明确的单词边界:

new RegExp('(?<!\\w)(?:' + Object.keys(CHARS).map(escape).join("|") + ')(?!\\w)', "g")

或者,或者,您可以依赖空白边界,这需要空白字符或两端的字符串开头/结尾:

new RegExp('(?<!\\S)(?:' + Object.keys(CHARS).map(escape).join("|") + ')(?!\\S)', "g") 

如果您需要进一步精确的边界模式,请根据您的要求选择解决方案并精确查看环视中的模式。

【讨论】:

  • 感谢您的详细解释。
【解决方案2】:

如果有空间要求,您可以将该要求添加到CHARS

const CHARS = {
  ":) ": "? ",
  "(:": "?",
  ":-)": "?",
  ":(": "?",
  "):": "?",
  ":-(": "?",
  ":/": "?",
}

convertEmoji = string => {
    const escape = s => s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")
    const pattern = new RegExp(
      Object.keys(CHARS).map(escape).join("|"),
      "g"
    )
    return string.replace(pattern, match => CHARS[match])
}

console.log(convertEmoji(":) Hello world!"))
console.log(convertEmoji(":)Hello world!"))

【讨论】:

  • 感谢您的回答。我无法在对象键中使用任何空格,因为按下空格键时会触发此功能。因此,在对象键中有一个空格字符需要按 2 次空格键才能用表情符号替换代码。
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 2018-12-15
  • 1970-01-01
  • 2020-08-20
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 2018-08-28
相关资源
最近更新 更多