将数字列表按照数字进行分割的句子。

huangapple go评论86阅读模式
英文:

splitting sentences of a number list by its numbers

问题

我对JavaScript还不太熟悉,但是我可以帮你翻译一下你的问题。你想知道如何在数字索引后添加换行符,使输出看起来像这样:

  1. foo.
  2. bar.
  3. 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:

  1. foo.
  2. bar.
  3. 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 = &quot;1. foo. 2. bar. 3. baz.&quot;;

console.log(text.replace(/(?&lt;!^)\s*(\d+\.\s+)/g, &#39;\n$1&#39;));

<!-- 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" (&#39;.\n$1&#39;).

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

console.log(

  &#39;1. foo. 2. bar. 3. baz.&#39;

    // - 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, &#39;.\n$1&#39;)
);

<!-- language: lang-css -->

.as-console-wrapper { min-height: 100%!important; top: 0; }

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年8月8日 23:36:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861103.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定