将字符串转换为表情符号

Converting string to emoji

我有以下功能,它用给定的表情符号字符替换字符串代码。

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! - 这里应该不起作用,因为表情符号代码没有正确的空格。

请帮我解决这个问题。

如果有 space 要求,您可以将该要求添加到 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!"))

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

如果要确保左右两侧没有紧邻的单词字符,则需要使用 (?<!\w)(?!\w) 环视表示的明确单词边界:

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

或者,您可以依赖空白边界,这需要空白字符或两端的 start/end 字符串:

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

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