skip to Main Content

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?

2

Answers


  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:

    const text = "1. foo. 2. bar. 3. baz.";
    
    console.log(text.replace(/(?<!^)s*(d+.s+)/g, 'n$1'));
    Login or Signup to reply.
  2. 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').
    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; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search