Escaping sequences in strings (simple solution!)

Hi all,

I’ve been trying to make a new line in a string in React for at least 10 hours over a week now. Have searched Google and this forum but finally resorting to seeking help.

There are solutions like:
" let newText = text.split('\n').map((item, i) => {return <p key={i}>{item}</p>;});" or
using DangerouslySetInnerHTML, it seems, but I am looking for a simple solution.

This is my string:
var quotes = [{“quote”: “Line one Line two Line three”,“author”: “Someone”}];

I am looking for this result:
“Line one
Line two
Line three”

Adding \n with or without spaces between Line one, Line two, and Line three did not work:
Also, I am not looking to do this in html with ‘open bracket br close bracket’.

I am using it here:
function changeQuote() {
$("#text").fadeOut(“slow”, function() {randomx = Math.floor((Math.random() * quotes.length));
$("#randomQuote").text(quotes[randomx].quote);
$("#author").text(quotes[randomx].author);

Everything works, except, I just can’t escape sequences in strings.

I appreciate any help,
Cheers

React already sanitises strings so you need to use dangerouslySetInnerHtml, the ugly syntax is intentional to force you to be careful.

@MD2901, a little hack for you:

<p key={i}><pre className="pre">{item}</pre></p>

CSS:

.pre {
  font-family: inherit;
  white-space: pre-line;
}

The code above is giving me the same result as:

var array = ["Senz1","Senz2","Senz3"];
document.getElementById("bullets").innerHTML = '<ul><li>' + array.join("</li><li>"); + '</li></ul>'; 

For:

var quotes = [{"quote": quote1","author": "author1"}, {"quote": "quote2","author": "author2"}];

It’s doing this:
quote1 - author1

  • Senz1
  • Senz2
  • Senz3

or

quote2 - author2

  • Senz1
  • Senz2
  • Senz3

I am looking to escape the sequence within the string. If I touch HTML as above, it will duplicate that HTML content to appear after all strings in the array, same as above. If it was possible for different HTML content to appear only when one random quote or another appears, that would work.

The simplest option would be for this would work:

var quotes = [{"quote": quote1\n paper \n rock\n scissors","author": "author1"}, {"quote": "quote2 \n car\n boat\n plane","author": "author2"}];

And would look like this:
quote1
paper
rock
scissors
author1

or if the other quote comes up, because this is being used:

$("#text").fadeOut(“slow”, function() {randomx = Math.floor((Math.random() * quotes.length));
$("#randomQuote").text(quotes[randomx].quote);
$("#author").text(quotes[randomx].author);

Then, that other result would be:
quote2
car
boat
plane
author2

Cheers :slight_smile:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

That’s what I’ve been trying to do for a week :slight_smile:
adding \n in there doesn’t do it hehe.

If you’re looking for that result, your line should contain \new line characters in the first place, like this:

var quotes = [{“quote”: “Line one\nLine two\nLine three”,“author”: “Someone”}];

Check this out, and let me know if that’s something you want to achieve:

const ArtificiallySplitParagraph = ({text}) => {
  const lines = text.split("\n").map(line => line.trim());
  return (
    <>
      { lines.map((line, i) => <p key={i}>{line}</p> }
    </>
  );
};

Which fixes the whitespace issue you have as well. Usage:

<ArtificiallySplitParagraph text={quote} />

Again, these things are here for a reason, it makes it hard so as to make XSS attacks hard, so you’re trying to find an easy way to bypass the sensible protections that are in place. What you are trying to do isn’t an issue re XSS, so it’s unfortunate that those protections affect you, but you’re trying to save yourself writing at most about four or five lines of basic code, just use either dangerouslySet or the component solution above (which would give you a much better level of control over text styling anyway) 🤷

Hey guys, thank you for still checking this out. I think Dan has a point there. Hoping for this code to be secure, I prefer the option of going with more code rather than using dangerouslySetInnerHtml.

Iiiked, yeah that link is awesome! and has the same idea! I have tried incorporating it into my code but having difficulty. Dan, have tried your ArtificiallySplitParagraph code also but having trouble incorporating it also. I think it’s likely that I’m still very noob at this and this is the reason I still have trouble! hrm

This is a simple version of my code for HTML, then CSS, then JS:

<div class="row" id='root'> 
  <div class="col-sm-6 col-md-6 col-lg-6"> 
    <div id="quote-box" class="container-fluid">
      <div id="text"><p><span id="randomQuote"></span></p></div>
      <div><p><span id="author"></span></p></div>
    </div>
  </div>
</div>

#quote-box {background-color: blue;border:1px solid #4d4d4d;border-radius:6px;color:#fff;padding-left:1em;};
.pre {font-family: inherit;white-space: pre-line;}

$(document).ready(changeQuote);
var quotes = [{"quote": "Paper\n Rock\n Scissors\n","author": "Details"}, {"quote": "Car\n Plane\n Rocket\n","author": "Details"}];
var randomx = 0;
function changeQuote() {
  $("#text").fadeOut("slow", function() {randomx = Math.floor((Math.random() * quotes.length));
  $("#randomQuote").text(quotes[randomx].quote);
  $("#author").text(quotes[randomx].author);
  $("#text").fadeIn("slow");});};

To make it work I use Jquery and React.

This sounds extremely disturbing :slight_smile: I would strongly suggest re-considering that decision.
It’s the same if you would say “To make it work I use Angular and React.” or “To make it work I use Windows and Mac.”

You see, when your $(document).ready() this absolutely doesn’t mean your react code is ready and in most of the cases I can imagine it would be 99.99% true. jQuery and React live in parallel universes both conceptually and literally. If you want to use both, you need to make 2 different projects, one in jQuery and one in React.

Perhaps I built a frankenthing :slight_smile:
The project works beautifully, with the exception of the lines not breaking.

If that a goal, then good for you :+1:

I just looked up what goad means. It’s not a goad. I originally had 2 projects, one with Jquery and another with React, and later I wanted the functionality of both in one page, which is what I have now.

If it’s possible break the line in the string in my code above (with additional code), that’s what I’m looking for. Have tried adding the other things mentioned above, to the code I posted above, but so far I’ve not been successful if making those work.

@MD2901, did you see the codepen example I’ve posted?

I mean, it’s just a react component so you just put it into your React code (and probably give it a better name) and give it a string of text and it renders that string as paragraphs, there isn’t much more to it than that, it’s just a basic thing

Also sharing @snigo concern re mixing jQuery and React, not sure how whether the way you’ve made things work is affecting things here

Hi, yeah it may be a basic thing, I am still learning basic things though. I my application I have both React and Jquery working well, but yeah, the only exception is my inability to escape a sequence inside a string.

To simplify things, I extracted the applicable code from my app to my code shown above. Now being free from any React aspect, it still has the same limitation as my app, which is that I’m still unable to escape the sequence. In other words, React is no longer a variable in the equation while the problem remains. As far as I can tell, what remains is just a bit of JS, HTML, CSS, and Jquery.

iiiked, yeah I opened the codepen example you posted. Some posts above I said I tried it, then again but couldn’t make it work. Will keep trying… probably missing a coma or something somewhere…

Ah hang on, I’ve only been half reading your responses, and I’m being stupid. Re any text with \n and HTML, it’s irrelevant whether you use React’s dangerouslySet or set it via JS DOM functions or whatever. \n can’t possibly work normally, it’ll just be ignored. @snigo suggested a slightly hacky solution. Otherwise you need to split the text and render as separate elements as I suggested (or insert br elements)

The larger question would by why are you trying to render text with newlines?