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

Viewed 208

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.

6 Answers

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

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)

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)

You could use regex match with:

Match prefix "- " but exclude from capture (?<=- ) and any number of character different of "\n" [^\n]*.

const str = `
- foo
- bar
`

console.log(str.match(/(?<=- )[^\n]*/g))

chunks.map((data) => {
    data = data.replace(/(\r\n|\n|\r|\\n|\\r)/gm, "");

   return data;
})

    const str = ` - foo
     - bar`;
     
     const result = str.replace(/([\r\n|\n|\r])/gm, "")
     console.log(result)

That should remove all kinds of line break in a string and after that you can perform other actions to get the expected result like.

const str = ` - foo
         - bar`;
         
         const result = str.replace(/([\r\n|\n|\r|^\s+])/gm, "")
         console.log(result)
         
         const actualResult = result.split('-')
         actualResult.splice(0,1)
         console.log(actualResult)
         
         

Related