I have a problem. My users can write things down in the textarea and I would like to make sure that the first line in the WYISWYG editor is an object in JSON, the second line is an object in the WYISYG and so on.
What is the actual problem?
I need to separately style the three lines, so I need to get the elements one by one as an output. The problem is that now I have one object with a long string that I have to divide in three lines, which I can't do.
To illustrate what I mean:
Textarea --> someone writes:
To get:
{"line 1":"<p>Hello<\/p>\"}
{"line 2":"<p>I am an example<\/p>\"}
{"line 3":"<p>Hello 2<\/p>\"}
Instead I get:
{"line 1":"<p>Hello<\/p>\n<p>I am an example<\/p>\n<p>Hello 2<\/p>\n"}
Could anyone help here?
Edit: I am parsing it like this:
openingtimes = parse(json["line1"] ?? "").documentElement!.text;
After getting the contents of the textarea, you can use .split("\n") to get the array of separate lines. (Note the use of " instead of '.)
If you then need to convert that array into an object, just create an empty object, loop through the lines array and add them to it.
Have a look at the different console.log()s output at every stage:
function getTextareaContentsAsArray() {
// Get the element
let textarea = document.getElementById('the_editor');
// Get the contents
let contents = textarea.value;
// Split by line ending
let lines_array = contents.split("\n");
console.log(lines_array);
// Convert array to array of JSON
let lines_object = {};
lines_array
// Remove empty lines
.filter((v) => v.length)
// Loop through all lines and add them to the_json object
.map((line, index) => {
lines_object[`line${index+1}`] = line;
});
console.log(lines_object);
let json_as_string = JSON.stringify(lines_object);
console.log(json_as_string);
}
<textarea id="the_editor" cols="50" rows="5"><p>Hello</p>
<p>I am an example</p>
<p>Hello 2</p>
</textarea>
<button id="the_button" onclick="getTextareaContentsAsArray()">Get contents as array of lines</button>