Home > Blockchain >  JavaScript '\n' madness
JavaScript '\n' madness

Time:07-13

I'm trying to convert a string like 'Some\nexample\nstring' into an array like ['Some', '\n', 'example', '\n', 'string']

But it's insane that I have to do this:

    let words = text.replace('\n', ' \\n ').split(/\s/);
    words = words.map(it => {
      if (it === '\\n') return '\n'
      else return it
    })
    // result: ['Some', '\n', 'example', '\n', 'string']

Because this doesn't work:

    const words = text.replace('\n', ' \n ').split(/\s/);
    // result: ['Some', '', '', 'example', 'string']

Nor this:

    const words = text.replace('\n', ' \\n ').split(/\s/);
    // result: ['Some', '\\n', 'example', 'string']

Nor this:

    const words = text.replace('\n', ' \\\n ').split(/\s/);
    // result: ['Some', '\\', '', 'example', 'string']

What gives?

CodePudding user response:

Here is a string match approach. We can alternatively match groups of whitespace or non whitespace characters.

var input = 'Some\nexample\nstring';
var parts = input.match(/\s |\S /g);
console.log(parts);

CodePudding user response:

If you want the split pattern to be included in the result, capture it, e.g.

console.log(
  'Some\nexample\nstring'.split(/(\n)/)
)

  • Related