我有一根绳子:
this.sentence = 'I have a brother, sister, a dog, and a cat.'
我想将其转换为数组,以便每个单词和每个标点符号都是一个单独的值。使用
.split(" ")
给我一个单词数组,但不会将每个逗号和点作为单独的值。
我怎样才能做到这一点才能得到这样的数组
["I", "have", "a", "brother", ",", "sister", ",", "a", "dog", ",", "and", "a", "cat", "."]
我真的不想使用
.match
和正则表达式,因为我需要在句子中包含特殊的波兰语字符
const string = 'I have a brother, sister, a dog, and a cat.';
const result = string.split(' ');
for (let i = 0; i < result.length; i++) {
if (result[i].includes(',')) {
result[i] = result[i].replace(',', '');
result.splice(i + 1, 0, ',');
i += 1;
}
if (result[i].includes('.')) {
result[i] = result[i].replace('.', '');
result.splice(i + 1, 0, '.');
i += 1;
}
}