print JS object in a div with new line instead of \n - javascript

I am printing some JS object in a div. JS object is having a key with value being a string with newline.
String
one
two
three
Expected value in div:
one
two
three
What I am getting in div
one\ntwo\nthree
Code:
const textarea = document.querySelector("#textarea");
const log = document.querySelector("#log");
textarea.addEventListener('keypress', (event)=>{
log.innerHTML = JSON.stringify({name:event.target.value});
});
<div id="log"></div>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

Newline characters are not permitted in JSON; JSON.stringify will never result in a string with a literal newline character. Stringifying something with a newline character will result in the output string containing a literal backslash character, followed by a literal n character, which is what you're seeing here.
If you actually need JSON.stringify, replace all \ns in it with actual newline characters.
Another problem is that newline characters do not normally result in actual newlines in the rendered HTML, for most elements. You might use a <pre> instead of a <div>, since <pre>s do render newlines in their contents as actual newlines:
const textarea = document.querySelector("#textarea");
const log = document.querySelector("#log");
textarea.addEventListener('keypress', (event) => {
log.textContent = JSON.stringify({
name: event.target.value
})
.replace(/\\n/g, '\n');
});
<pre id="log"></pre>
<br>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>
(keep in mind that the contents of the #log element will not be valid JSON - you won't be able to copy its contents and JSON.parse it)

Use escape character \
{"name":"one\\ntwo\\nthree"}

You have to replace \n with <br>
Should use keyup instead of keypress otherwise you could only get the current value in the textarea
const textarea = document.querySelector("#textarea");
const log = document.querySelector("#log");
textarea.addEventListener('keyup', (event)=>{
log.innerHTML = event.target.value.replace(/\n/g, '<br>')
});
<div id="log"></div>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

just replace keypress by keyup
const log = document.querySelector("#log");
const textarea = document.querySelector("#textarea");
textarea.addEventListener('keyup', (event)=>{
log.innerHTML = JSON.stringify({name: event.target.value.replace(/\n/g, '<br>')})
});
<div id="log"></div>
<br>
<textarea name="" id="textarea" cols="30" rows="10"></textarea>

Related

Preserve line breaks while substituting anything except the first letter and punctuation marks

jQuery("#memorize-form").submit(function(){
var text = jQuery("#n-text").val();
var substitute_with = "_";
const regex = /\B\w/g;
var result = text.replaceAll(regex, substitute_with);
jQuery("#result").html(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="memorize-form" action="" method="get">
<textarea id="n-text" rows="10"></textarea>
<button id="memorize-submit">Convert</button>
</form>
<span>Result: </span><span id="result"></span>
This code replaces all the letters except the first on with the underscore. The punctuation should be made intact.
The text is input by the user.
The problem with it is that the text contains a line break, the line break is not preserved. It should be preserved.
Try this:
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.
The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters.
P.S.: The result disappears from the screen. Why is this?
Very simple, just detect \n and replace it with <br/>
jQuery("#memorize-form").submit(function(e){
e.preventDefault(); //prevents form submit
e.stopImmediatePropagation(); //prevents form submit
var text = jQuery("#n-text").val();
var substitute_with = "_";
const regex = /\B\w/g;
var result = text.replaceAll(regex, substitute_with);
//recommended way
if(result.match(/[^\r\n]+/g)){ //check for \n and replace it with <br>
result = result.replaceAll('\n','<br/>');
//result = result.replace('\r','<br/>'); handle \r if needed
}else{
//not recommended way
//check for . `fullstops` and add a br.
//if(result.includes('.')){
// result = result.replace('.','<br/>');
//}
}
jQuery("#result").html(result);
});
Tested code!

How to pass input from one textarea to another's output?

I just started learning JS again and I've run into this problem while making an app.
I can't pass input from one textarea to second textarea which is output. I want to make the text uppercase on output. I tried to modify code from w3 but I want to make it without button so it looks cleaner.
What I want to achieve:
User writes something in input
His text is copied to output and changed to uppercase letters
HTML
<h3>INPUT</h3>
<textarea id="inputText" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
<h3>OUTPUT</h3>
<textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>
JS
document.getElementById("inputText") = str;
var res = str.toUpperCase();
document.getElementById("outputText").innerHTML = res;
Not sure what part of your JavaScript that is, but str is not defined. Here's a working version.
const uppercaseEl = document.getElementById('outputText')
function update(el) {
uppercaseEl.value = el.value.toUpperCase()
}
<h3>INPUT</h3>
<textarea id="inputText" oninput="update(this)" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
<h3>OUTPUT</h3>
<textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>
Ok so for that you will first have to make some kind of button that will then trigger the script to run so I have done that in the following:
<h3>INPUT</h3>
<textarea id="inputText" placeholder="input" cols="70" rows="10" wrap="on"></textarea>
<button onclick="MakeUpper()">Enter</button>
<h3>OUTPUT</h3>
<textarea id="outputText" placeholder="output" cols="70" rows="10" wrap="on" readonly></textarea>
Then for the script it shall be a normal function:
function MakeUpper() {
var upperCase = document.getElementById("inputText").value;
var upperCase = upperCase.toUpperCase();
document.getElementById("outputText").innerHTML = upperCase;
}
Hope this solved your query also sorry for any bad code formatting as this is my first time answering a question on the website
You can subscribe to the textarea change event
document.querySelector("#inputText").addEventListener("change", (event) => {
document.querySelector("#outputText").textContent = event.target.value;
});
and when that event appears, change the output text's inner text
BUT the change will only appear after the textarea loses focus, so you could react to the keyup event instead, that will make it real-time :)
document.querySelector("#inputText").addEventListener("keyup", (event) => {
document.querySelector("#outputText").textContent = event.target.value;
});
Or you can use your code, where you just swaped sides, forgot the keyword and you want the element's value, not the whole element
let str = document.getElementById("inputText").value;
let res = str.toUpperCase();
document.getElementById("outputText").textContent = res;
Use textContent instead of innerHTML as it's safe
and I use let instead of var, you should too, look it up
Your first assignment isn’t valid; the variable name (str) always goes on the left.
var str = document.getElementById("inputText").value
You also need .value to get the value of the input. More explicitly:
var inputTextarea = document.getElementById("inputText")
var str = inputTextarea.value
Similarly you need to set .value, not .innerText:
var outputTextarea = document.getElementById("outputText")
outputTextarea.value = str
This will run now, but your central problem (it doesn’t update when you type) persists, because your code just runs once when the page loads. So you copy the value of nothing, then your script stops. You need it to run again whenever the input changes, which looks like this:
var inputTextarea = document.getElementById("inputText")
var outputTextarea = document.getElementById("outputText")
function copyText () {
var upper = inputTextarea.value.toUpperCase()
outputTextarea.value = upper
}
inputTextarea.addEventListener('change', copyText)
In the first line of your js you are trying to do a very bad thing. This operation is called assignment. You can assign a value to a variable, but you are trying to the opposite things.
You want to practice, but in order to do that you need to learn some programming theory first: Variables, operators, functions...
https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web that would be a good start. Don't skip anything.

Converting \n to <br/>

I'm having problem converting \n to a < br / >
function format() {
var text = document.getElementById("formatArea").value;
text.replace("\n", "<br/>");
document.getElementById("resultArea").value = text;
}
<textarea rows="20" cols="80" id="formatArea">
</textarea>
<textarea rows="20" cols="80" id="resultArea">
</textarea>
<button onclick="format()">Click to create HTML breaks</button>
Appreciate any help, i'm not very experienced in JS yet.
You have 2 issues here.
Firstly, replace does not change the original string, it returns a modified string. (Documentation link : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)
Secondly, if you put a string in the first parameter of replace, it will only replace the first occurence. If you want to replace them all, use a Regular Expression.
So you should have this :
function format() {
var text = document.getElementById("formatArea").value;
text = text.replace(/\n/g, "<br/>");
document.getElementById("resultArea").value = text;
}
The g ("global") flag on a regular expression is used to match all occurences.
Replace all was something I didn't understand when I started learning JavaScript too!
TL;DR There isn't a replaceAll function in JavaScript. But replace accepts something called regular expressions.
To replace all foos with bars in a string you have to do .replace(/foo/g, "bar"). /foo/g will match all the "foo"s and will replace them with bar. g is called flag and it it means global, meaning you match them all.
If you want to replace \ns you have to do: .replace(/\n/g, "<br/>"), like we did for foo:
text = text.replace(/\n/g, "<br/>")
Also, you have to assign the new string to the old string, as replace would not modify the original variable value:
function format() {
var text = document.getElementById("formatArea").value;
text = text.replace(/\n/g, "<br/>");
document.getElementById("resultArea").value = text;
}
<textarea rows="20" cols="80" id="formatArea">
</textarea>
<textarea rows="20" cols="80" id="resultArea">
</textarea>
<button onclick="format()">Click to create HTML breaks</button>
Use /\n/g for global replace and you have also missed the assignment of the changed text value in text itself, thus the replaced text was not taking effect. You need to assign the replaced value like text = text.replace(/\n/g, "<br/>"); :
function format() {
var text = document.getElementById("formatArea").value;
text = text.replace(/\n/g, "<br/>");
document.getElementById("resultArea").value = text;
}
asd
<textarea rows="20" cols="80" id="formatArea">
</textarea>
<textarea rows="20" cols="80" id="resultArea">
</textarea>
<button onclick="format()">Click to create HTML breaks</button>

how to modify the following script to be able of receive parameters with spaces?

The main idea is to copy three parameters into my fist text area called: text
<textarea cols="70" rows="15" id="text" ></textarea>
to the press my button called: Generate tables,
<button id="generate">Generate tables</button><br>
and getting the result in the second text area called: out1,
I prove it whit the following parameters:
ford volvo bmw
and I got the right result:
"Svolvo|ford~E~bmw" "ford~SNRF"
The problem is that this time I with to receive three parameters but they could contain spaces as follows:
"ford 34" "volbo 45" "bmz 34"
So with this input I would like to produce the following desired output:
"Svolvo 45|ford 34~E~bmw 34" "ford~SNRF"
Note that the first parameter has two blank spaces and i want to preserve it in the output, when is the case, for every parameter,
However with my current regex that is:
/(\S+)\s+(\S+)\s+(\S+)/g
I am getting:
"S34"|"ford~E~"volbo" ""ford~SNRF" "S"bmz|45"~E~34"" "45"~SNRF"
Which is not right, I would like to appreciate any suggestion to fix my function:
var generate = document.getElementById('generate');
var input = document.getElementById('text');
var output = document.getElementById('out1');
generate.onclick = function() {
var text = input.value;
text = text.replace(/(\S+)\s+(\S+)\s+(\S+)/g,
'"S$2|$1~E~$3" "$1~SNRF"');
output.textContent = text;
};
<textarea cols="70" rows="15" id="text"></textarea>
<div cols="3" rows="15" id="out1" style="width:80%; white-space:pre; color:Lime"></div>
<div class="wrapper">
<button id="generate">Generate tables</button>
</div>
You could use this regular expression, which works for the original case, but also for when you have wrapped words in double quotes, in which case the part between quotes is taken as one part:
/(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))/g
The replacement string needs to change to this, as there are now more capture groups:
'"S$3$4|$1$2~E~$5$6" "$1$2~SNRF"'
Explanation
This part identifies one term. It is repeated for the other two terms:
(?:"(.*?)"|(\S+))
This consists of two options split by |. If the string starts and ends with a quote, the first option is taken, else it goes for the second (original) option.
In both cases there is a capture group, but in the first case the double quotes are excluded. The outer brackets are only to tell the | operator what its scope is; it is not captured as a group ((?:).
var generate = document.getElementById('generate');
var input = document.getElementById('text');
var output = document.getElementById('out1');
generate.onclick = function() {
var text = input.value;
text = text.replace(/(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))\s+(?:"(.*?)"|(\S+))/g,
'"S$3$4|$1$2~E~$5$6" "$1$2~SNRF"');
output.textContent = text;
};
<textarea style="width:100%" id="text">ford "volbo 45" "bmz 34"</textarea>
<div id="out1" style="width:80%; white-space:pre; color:Lime"></div>
<button id="generate">Generate tables</button>

Javascript replace every line of value

So I have this script which has to find some text on the first textarea (right away when text is pasted), then replace it with another one and give the result to another textarea.
The problem is that it's replacing the text only for the first line. And I want it to replace it on the All lines.
My code: (doesn't work on JSfiddle, but do on HTML)
<script>
function go()
{
var str = document.getElementById("a").value;
resa=str.replace("http://","www.");
resb=resa.replace(".com","");
document.getElementById("b").value=resb;
}
</script>
<textarea rows="10" cols="140" onkeyup="go()" id="a">
</textarea>
<textarea rows="10" cols="140" onkeyup="go()" onclick="this.focus();this.select();" id="b">
</textarea>
So if you try to enter https://google.com in every line you will get right text on the other textarea, but only in the first line.
You need to do a global replace.
var str = document.getElementById("a").value;
var resa=str.replace(/http\:\/\//g,"www.");
var resb=resa.replace(/\.com/g,"");
It's not that only the first line is replaced. The problem is you're only replacing the first occurrence.
Change to use a regex to replace all:
var resa = str.replace(new RegExp('http://', 'g'), 'www.');
var resb = resa.replace(new RegExp('.com', 'g'), '');
document.getElementById("b").value = resb;

Categories

Resources