提问人:baguette 提问时间:8/8/2023 最后编辑:Peter Seligerbaguette 更新时间:8/11/2023 访问量:63
将数字列表的句子按其数字拆分
splitting sentences of a number list by its numbers
问:
我对 JavaScript 很陌生, 假设我有这个:
const text = "1. foo. 2. bar. 3. baz";
这是调用 API 返回的 JSON, 有没有办法在数字索引后添加一个新行,以便我在输出时看起来像这样:
- 呸呸。
- 酒吧。
- 巴兹。
我想让它像一个
我试图用“.”分开,但它不起作用并反复给予
1.foo
1.foo
3.baz
3.baz
有什么办法可以做到吗?
答:
1赞
Alexander Nenashev
8/8/2023
#1
您可以使用正则表达式,并用空格替换所有数字,用新行 + 匹配字符替换后点。此外,您可能还想修剪前缀空格:
const text = "1. foo. 2. bar. 3. baz.";
console.log(text.replace(/(?<!^)\s*(\d+\.\s+)/g, '\n$1'));
评论
0赞
baguette
8/9/2023
啊谢谢,请问一下之间是不是没有空格。还有我怎么能拆分它这个词?比如 ' const text = “1.foo 2.bar 3.baz”;“,并且想要在那里获得相同的结果,它需要什么?
0赞
Alexander Nenashev
8/9/2023
@baguette固定的,不能在没有空格的情况下拆分
0赞
baguette
8/10/2023
啊,谢谢ssssss
0赞
Peter Seliger
8/9/2023
#2
OP 所需的结果可以通过简单的替换
任务来实现,该任务...
console.log(
'1. foo. 2. bar. 3. baz.'
// - see ... [https://regex101.com/r/3LnxBQ/1]
// - replace each dot followed by at least one
// space and at least one digit by a dot, a
// new line and the captured digit sequence.
.replace(/\.\s+(\d+)/g, '.\n$1')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
评论
0赞
baguette
8/10/2023
啊,谢谢ssssss
评论