英文:
splitting sentences of a number list by its numbers
问题
我对JavaScript还不太熟悉,但是我可以帮你翻译一下你的问题。你想知道如何在数字索引后添加换行符,使输出看起来像这样:
- foo.
- bar.
- baz.
你尝试使用"."进行分割,但是没有成功,而是得到了重复的结果。你想知道是否有其他方法可以实现这个目标。
英文:
i am quite new to javascript,
Lets say i have this:
const text = "1. foo. 2. bar. 3. baz";
this is a json returned from calling api,
is there any way to add a new line after a number index so that i can look like this when output:
- foo.
- bar.
- baz.
i want to make it like a
i tried to split by "." but it does not work and repeatedly giving
1.foo
1.foo
3.baz
3.baz
is there any way to do that?
答案1
得分: 1
你可以使用正则表达式,将所有数字替换为前面的空格和后面的点,并换行+匹配字符。此外,你可能还想去掉前缀的空格:
const text = "1. foo. 2. bar. 3. baz.";
console.log(text.replace(/(?<!^)\s*(\d+\.\s+)/g, '\n$1'));
这段代码会将文本中的数字列表格式化为每行一个条目的形式。
英文:
You could use a regex and replace all numbers with a white spaces before and a dot after with a new line + the match characters. Also you would probably want to trim the prefix white spaces:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const text = "1. foo. 2. bar. 3. baz.";
console.log(text.replace(/(?<!^)\s*(\d+\.\s+)/g, '\n$1'));
<!-- end snippet -->
答案2
得分: 0
OP的要求可以通过一个简单的replace
任务来实现,该任务会将“每个点后面至少有一个空格和至少一个数字”的部分(/\.\s+(\d+)/g
)替换为“一个点,一个换行符和捕获的数字序列”('.\n$1'
)。
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')
);
请注意,这是一个JavaScript代码示例,用于演示如何使用replace
方法实现所需的替换操作。
英文:
The OP's required result can be achieved by a simple replace
task which ...
- does (globally) replace "each dot followed by at least one space and at least one digit" (
/\.\s+(\d+)/g
) by "a dot, a new line and the captured digit sequence" ('.\n$1'
).
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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')
);
<!-- language: lang-css -->
.as-console-wrapper { min-height: 100%!important; top: 0; }
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论