我想分割以下两个字符串,并在每个索引号的末尾加上.
(点)。
let str1 = "1. sun ; moon ; star ; god ; goddess";
// will work with both the string
let str2 = "sun; moon; star; god; goddess;";
结果应该是这样
let result = "1. sun\n2. moon\n3. star\n4. god\n5. goddess.";
或执行以下操作
1. sun.
2. moon.
3. star.
4. god.
5. goddess.
更新:我将其拆分,但未能在每个单词中添加索引号。由于单词是随机的,例如一个可以有3个单词,另一个可以有5个单词,依此类推...
答案 0 :(得分:2)
您可以通过在重新添加之前从字符串中删除列表编号来实现。这是一个示例:
const formatList = list => {
list = list
// split the string
.split(';')
// filter out empty list items
.filter(Boolean)
// Iterate over the list items to format them
.map((item, index) => {
// Start with the index (+1 one to start from 1)
return (index + 1)
// Add the dot and the space
+
'. '
// Add the list item without any number+dot substring and any extra space
+
item.replace(/\d+\./g, '').trim()
// Add a final dot (even if list should not usually have ending dots)
+
'.'
})
// Join back the list items with a newline between each
.join('\n');
return list;
};
let str1 = "1. sun ; moon ; star ; god ; goddess";
let str2 = "sun; moon; star; god; goddess;";
let result = "1. sun.\n2. moon.\n3. star.\n4. god.\n5. goddess.";
console.log(formatList(str1), formatList(str1) === result);
console.log(formatList(str2), formatList(str2) === result);
答案 1 :(得分:2)
我们可以分割正则表达式/\s*;\s*/g
,然后处理数字可能已经在map
函数的列表项中出现的可能性,如第一个示例一样。
let str1 = "1. sun ; a moon ; star ; god ; goddess ; ";
const result = str1.split(/\s*;\s*/g)
.filter(Boolean)
.map((e, i) => `${/^\d+\./.test(e) ? "" : i + 1 + ". "}${e}.`)
.join("\n");
console.log(result);