gpt4 book ai didi

javascript - 将表情符号与文本分开的正则表达式

转载 作者:行者123 更新时间:2023-11-28 16:16:16 25 4
gpt4 key购买 nike

我正在尝试在 Javascript 中创建一个正则表达式,以将任何出现的 :) 与周围的文本分开。

鉴于以下情况:

:)This is a line of text :) with several smileys in it :). So there.,:):)

我想要得到结果 8 组:

  1. :)
  2. 这是一行文本
  3. :)
  4. 里面有几个笑脸
  5. :)
  6. 。就这样。,
  7. :)
  8. :)

目前我使用 ([^:)]+) ,它仅对周围的文本进行分组,而没有表情符号。我可以进行哪些调整以使表情符号也分组?

最佳答案

我建议:

var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
matches = str.split(/(\:\))/);
console.log(matches);​

JS Fiddle demo .

添加了过滤以删除上面的空匹配项:

var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
matches = str.split(/(\:\))/),
matched = [];
for (var i = 0, len = matches.length; i < len; i++) {
if (matches[i].length) {
matched.push(matches[i]);
}
}
console.log(matched);​

JS Fiddle demo .

进一步的版本,具有实际的屏幕输出:

var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)",
matches = str.split(/(\:\))/),
matched = [], li,
list = document.createElement('ol');
document.body.appendChild(list);
for (var i = 0, len = matches.length; i < len; i++) {
if (matches[i].length) {
matched.push(matches[i]);
li = document.createElement('li');
txt = document.createTextNode(matches[i]);
li.appendChild(txt);
list.appendChild(li);
}
}
console.log(matched);​

JS Fiddle demo .

关于javascript - 将表情符号与文本分开的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11384742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com