Home > front end >  Is there a way to remove a newline character within a string in an array?
Is there a way to remove a newline character within a string in an array?

Time:12-21

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.

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

   return data;
})

CodePudding user response:

    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