1

I'm developing an app where at some point app receives a string from Facebook Graph API.

String looks like that:

"Some text some text, some text.\n\nMore text and more\n\nAnd little bit more".

How can I replace \n\n with line break what actually works in code?

I know how to replace this with something:

var ret = stringToReplace.replace('\n\n','<br />');

But how can i replace it with working line break. I have tried to replace with '\n' '\r\n'. Every replacement just acts like usual text. For example:

"Some text some text, some text.<br />More text and more<br />And little bit more"
Vahid Boreiri
  • 3,418
  • 1
  • 19
  • 34
Calm
  • 51
  • 1
  • 2
  • 7

4 Answers4

13

I know I am pretty late to the party but I recently stumble across the same problem when I was fetching data with \n from a database. The solution that worked for me was just to run the replace method and replace incoming \n with jsx \n. So in your case it would be:

var ret = stringToReplace.replace(/\\n/g,'\n');

Looks like a really stupid solution but it worked for me.

  • 1
    @contrl What happens is that `\n` is initially interpreted as a string when it is fetched from the database. However, when calling `replace`, `\n` can then be perceived as a new line. – Kevin H Griffith Oct 19 '20 at 11:49
  • this is pretty weird, but it actually did the trick for me. – Hinrich Oct 23 '20 at 09:55
  • @KevinHGriffith I still don't fully grasp the mechanism underlying this behavior but thanks for your answer :) – contrl Oct 30 '20 at 09:58
  • @contrl sorry for not being able to fully explain why it works. Glad I could help you out though. :) – Kevin H Griffith Nov 06 '20 at 15:26
6

I test the following code and it works. You should just wrap your text in a <Text> component.

export default class App extends React.Component {
  text = "Some text some text, some text.\n\nMore text and more\n\nAnd little bit more"

  render() {
    return (
      <View style={styles.container}>
        <Text>
          {this.text}
        </Text>
      </View>
    );
  }
}

The result of this code is like this: enter image description here

Vahid Boreiri
  • 3,418
  • 1
  • 19
  • 34
  • Yes, this solution works, when i enter my text manually, but in my app this text comes from Facebook Graph API and i can't change it manually. – Calm Feb 20 '19 at 22:51
1

React/ React native has line break object {`\n`}, see below code sample

<Text style={{margin: 10}}>
 Our Address {`\n`}

xxx, Clear Water Bay Road {`\n`}
Clear Water Bay, Kowloon {`\n`}
HONG KONG {`\n`}
Tel: + xx {`\n`}
Fax: + xx {`\n`}                    
</Text>
hang-coder
  • 420
  • 4
  • 8
  • This works well, thanks! My only comment is that you don't really need the backticks, since you're not doing any variable evaluation - single quotes would be sufficient. – Westy Aug 30 '21 at 19:35
0

Use template literals/backticks as wrapper instead of double-quotes. It worked for me.