Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
JavaScript '\n' madness

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!