Converting \n to <br/> - javascript

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>

Related

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.

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

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>

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 - Convert br Tags To New Lines

I have a JavaScript function that looks like this:
function onAfterTranslate(item, translator) {
var thing = item.translated_text;
document.myform.keywords.value = "Translated Text:\r\n\r\n" + thing.replace(/<br>/g, "\r\n");
}
The parameter named item is an object, which includes an property called translated_text.
These are the contents of this variable:
mono <br> toro <br> gato <br> perro <br> elefante
What I want to do is convert the br tags to newline characters. (Ideally, it should look for optional spaces immediately before and after the br tag, and it should also accept any of the valid formats of br tag that exist, but that's not crucial at the moment.)
However, the replace command in the above code is not working, and I can't work out why.
If I remove the replace command so the line ends with the variable name thing, then it behaves as expected, updating the textarea box in my form with the correct value.
Even if I try replacing the letter "o" with an asterisk, it still doesn't work, which would suggest I'm doing something fundamentally wrong here.
Any suggestions?
You can use \s to look for spaces and ? for "preceding char may occur once or not". The regex is here below.
/\s?(<br\s?\/?>)\s?/g
Here below is an example with all possible br tags: <br>, <br /> and <br/> with some spaces in between.
var input = document.getElementById('input').value;
console.log(input);
document.getElementById('output').value = input.replace(/\s?(<br\s?\/?>)\s?/g, "\r\n");
textarea {
width: 400px;
height: 100px;
}
<h3>input</h3>
<textarea id="input">
fooo <br> bar <br> lorum ipsum dolor.
valar durum <br /> kel alar fol <br /> durom <br />.
a bread of kebab is tasteful !<br/>
EOL
</textarea>
<hr />
<h3>output</h3>
<textarea id="output"></textarea>
try
var text = "mono <br> totono <br> gato <br> elefante"
console.log( text.split( "<br>" ).join( "\n" ) );
and for trimming white spaces
text.split( "<br>" ).map( function(val){ return String(val).trim(); } ).join( "\n" );
for putting this in a textarea
document.body.innerHTML += "<textarea>" + text.split( "<br>" ).map( function(val){ return val.trim() } ).join( "\n" ) + "</textarea>" ;
So, it turns out the replace function was essentially fine (but enhanced now thanks to your contributions) - it was the format of the input data that was not what I was expecting.
I thought that the variable item.translated_text was an array element (because when I echoed it to the screen, I saw the value I was expecting), but it turned out it was actually an array, as I found out when I displayed the length of the variable and found it was only 1.
I now suspect that the item variable was a JSON construct and not a regular array, as I first thought.
Sorry if I wasted anyone's time on this.

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