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

220
Views
Is there a way to remove a newline character within a string in an array?

I am trying to parse an array using Javascript given a string that's hyphenated.

- foo
- bar

I have gotten very close to figuring it out. I have trimmed it down to where I get the two items using this code.

 const chunks = input.split(/\ ?\-\ ?/);
 chunks = chunks.slice(1);

This would trim the previous input down to this.

["foo\n", "bar"]

I've tried many solutions to get the newline character out of the string regardless of the number of items in the array, but nothing worked out. It would be greatly appreciated if someone could help me solve this issue.

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

0

You could loop over like so and remove the newline chars.

const data = ["foo\n", "bar"]

const res = data.map(str => str.replaceAll('\n', ''))
console.log(res)

about 4 years ago · Juan Pablo Isaza Report

0

Instead of trimming after the split. Split wisely and then map to replace unwanted string. No need to loop multiple times.

const str = ` - foo
 - bar`;
let chunks = str.split("\n").map(s => s.replace(/^\W+/, ""));
console.log(chunks)

let chunks2 = str.split("\n").map(s => s.split(" ")[2]);
console.log(chunks2)

about 4 years ago · Juan Pablo Isaza Report

0

You could for example split, remove all the empty entries, and then trim each item to also remove all the leading and trailing whitespace characters including the newlines.

Note that you don't have to escape the space and the hyphen.

const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
  .filter(Boolean)
  .map(s => s.trim());

console.log(chunks);

Or the same approach removing only the newlines:

const input = `- foo
- bar`;
const chunks = input.split(/ ?- ?/)
  .filter(Boolean)
  .map(s => s.replace(/\r?\n|\r/g, ''));

console.log(chunks);

Instead of split, you might also use a match with a capture group:

^ ?- ?(.*)

The pattern matches:

  • ^ Start of string
  • ?- ? Match - between optional spaces
  • (.*) Capture group 1, match the rest of the line

const input = `- foo
- bar`;
const chunks = Array.from(input.matchAll(/^ ?- ?(.*)/gm), m => m[1]);
console.log(chunks);

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!