如何在不更改文本内容的情况下使用拆分

时间:2018-08-13 09:57:11

标签: javascript

我有这样的文字:

let text = ":wink: Is that true? :like: I never heard about that, as I know some country like: VN, Indonesia, ThaiLan".

:眨眼::喜欢:是显示表情符号的代码。现在,我使用split将秘密转换成这样的数组:

const myArray = text.split(':')

和结果:

myArray = ["", "wink", " Is that true? ", "like", " I never heard about that, as I know some country like", " VN, Indonesia, ThaiLan"]

如您所见,字符''不见了,当从文本转换为数组时,如何保持':',在这种情况下,我希望结果应该是:

myArray = [":wink:", " Is that true? ", ":like:", " I never heard about that, as I know some country like:", " VN, Indonesia, ThaiLan"]

1 个答案:

答案 0 :(得分:1)

尝试使用match代替:先匹配冒号,再跟非冒号,再匹配最后一个冒号,或者匹配所有内容,直到:word:之后:

let text = ":wink: Is that true? :like: I never heard about that, as I know some country like: VN, Indonesia, ThaiLan";
console.log(text.match(
  /:\w+:|.+?(?=:\w+:|$)/g
));