1

I am having trouble removing line breaks from my text in javascript. Here is an example of the data I am working with:

0: "Christian Pulisic"
1: "↵"
2: "From Wikipedia, the free encyclopedia"
3: "↵" 
4: "Christian Pulisic"
5: "↵"
6: "Personal information"
7: "↵"
8: "Full name   Christian Mate Pulisic[1]"

Obviously, the line spaces/breaks or whatever you call them, are polluting the data I am getting.

I cannot get the following function to recognize the line breaks and replace it with a "" which I then can very easily remove from the array through another function I run my data through.

This is the code I am currently using that is not working:

for (i in cleanArray){
    cleanArray[i].replace(/(\r\n|\n|\r)/gm,"")
};

console.log(cleanArray);
1
  • 1
    The replace() method returns a new string, it doesn't change the original one. Commented Feb 8, 2016 at 3:15

2 Answers 2

3

cleanArray[i].replace(/(\r\n|\n|\r)/gm,"") will return a new string. Furthermore, strings are immutable in JavaScript. Change it to

for(var i = 0; i < cleanArray.length; ++i)
    cleanArray[i] = cleanArray[i].replace(/(\r\n|\n|\r)/gm,"")
Sign up to request clarification or add additional context in comments.

1 Comment

or a bit shorter: cleanArray.map(i => i.replace(/(\r\n|\n|\r)/gm, "")
1

Assuming the characters shown as "↵" are actual newlines

Use Array#filter with String#trim

var newArr = arr.filter(el => el.trim());

3 Comments

Tried this and it did not work: 'var cleanerArray=[]; for (i in cleanArray){ cleanerArray.push(cleanArray[i].trim) }; console.log(cleanerArray);'
cleanerArray.push(cleanArray[i].trim) note that the function trim is not called. Use cleanerArray.push(cleanArray[i].trim())
@Lance You need to call trim() ^^^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.