Cypherjac
Cypherjac

Reputation: 879

Javascript function: use newlines as \n instead of actually rendering them

I am working on a function that receives text from a textarea input with an aim of retaining newline characters. The function then takes the text as an argument to the function, for example: function get_text(val){ ... }. The value being received from the textarea is:

$('#textarea').val();

Such that on the click of a button, the value in the textarea is passed to the get_text() function, for example:

$('#button').click(function(){
    get_text($('#textarea').val());
});

Then the function is meant to use the newline characters which are retained since the value is from a textarea. But here is where the problem comes in, when I pass the value of the textarea to the get_text() function, I get an error in the console stating: Unexpected identifier because the argument has been split over a few lines, for example:

If the text in the input is: (Line 1)My (Line 2)text (Line 3)is (Line 4)here

The function takes the text and outputs the newline characters:

get_text("My   --- (×)Error appears here
text
is
here");

I'm trying to use the newline characters from the textarea in the function which performs some task after every newline character is encountered, so getting rid of the newlines is not an option unless there is another way to perform the task.

The only problem here is actually passing the text into the function, for example:

get_text($('#textarea').val());
--- should result to ---
get_text('My\ntext\nis\nhere');
--- instead of actually outputting the newlines ---

Which works well with the function. Is there a way to pass the text to the function without printing the newlines but instead show them as \n ?

This is the get_text function:

function get_text(val){
let n = /[\n]/;
let i;
let inner = [];
for(i = 0; i < val.length; i++){
inner.push('<span>' + val[i] + '</span>';
if(n.test(val[i]) == true){
inner.push('<span class="newline">' + val[i] + '</span>';
}
}
return inner.join("");
}

And again, the problem is not even in the function, it is only when the value is passed to the function, it gets split into lines ... and no, I am not using eval

Yes I get the error only after getting it from a form

enter image description here

Upvotes: 0

Views: 582

Answers (2)

user120242
user120242

Reputation: 15268

MDN Template Literals

Template literal syntax allows your string to span multiple lines using the ` backticks as the container, which should avoid your problem. I would still recommend escaping the string and/or not mixing the server-side templating code and JavaScript code like that, especially not embedding form data as JS code verbatim. You can at least serialize it with json_encode or something similar.

You could also use JSON.stringify of the form data, and then JSON.parse it afterwards.

let val = `My
test
is
here`;

get_text(`My
text
is
here`);

You're missing parens and you're not using .test right. It takes the string, not a boolean comparison, and returns a boolean if it matches.
Also, if you want line breaks you should be using <br>. Putting a newline in a <span> will just collapse. It will not insert a line break in the rendered output. Unless you're using some CSS style like a float break that does the line break for you.

function get_text(val) {
  let n = /[\n]/;
  let i;
  let inner = [];
  for (let i = 0; i < val.length; i++) {
    inner.push('<span>' + val[i] + '</span>');
    if (n.test(val[i])) {
      inner.push('<span class="newline">' + val[i] + '</span>');
    }
  }
  return inner.join("");
}

console.log(
  content.innerHTML = get_text(`My
text
is
here`)
)
.newline::after {
  content: '\\n'
}
<div id="content"></div>

Upvotes: 1

FZs
FZs

Reputation: 18619

You can simply replace them with the backslash (\) and n characters literally.

To create a \ in a literal, escape it with itself, i.e. \\.

So,

$('#textarea').val().replace(/\n/g, '\\n')

Upvotes: 1

Related Questions