line breaks using javascript strings - javascript

I m breaking a line in javascript using \n for example: -
text = "this is a test" + "\n" + "another test";
and to show that in html i m using the code
text = text.replace('\n' , '<br>');
but the text i m getting is without the br
when checking in firebug console i get is with line break(\n not shown but newline created)
how can i place line breaks using \n or i have to do some custom code instead of \n
thanks

var newText = text.replace(/\n/g , "<br>");

use double quotes to not escape the \n
try this:
text = text.replace("\n" , "<br>");

/\r\n|[\r\n]/g <- this is what I use. I am a pessimist..

Related

Javascript substring replace and output

Hi guys I wonder how to reconstruct string. I need to replace br tag inside string with '\n' new line character. So I'm simply doing it like this:
let a='Some<br>Text'
let b=a.replace(/<br>/gi, '\n');
But when I try to make an output to console this way:
console.log(JSON.stringify(b))
It shows the string like this:
Some\nText
But if I'm doing output this way:
console.log(b)
It returns:
Some
Text
So why? And is it possible to use console.log(JSON.stringify(b)) to show the string in a proper way. I mean like this:
Some
Text
Because the stringify method converts all the characters to string, so you wont see line breaks as expected. If you want to display your text on the same line, you can just replace (inside your regexp replacer) the newline '\n' with an empty space ' '
just replace br with an empty space instead of \n, since \n means a new line.This is why your second word starts from new line
let a='Some<br>Text'
let b=a.replace(/<br>/gi, " ");
output
Some Text

How to create whitespace inside a JSON

I want to put a line of space or blanks between the values. Because they're all leaving together right now.
My example:
data: JSON.stringify({
"sessionID":xxxxx,
"synchronize":false,
"sourceRequest":{
"numberOrigin":xxxxxx,
"type":"x",
"description":test + "\\n" + test2 "\\n" + test3 "\\n" + test4,
"userID":xxxxxxxx,
"contact":{
"name":"xxxxxxxxxxxxxxxxx",
"phoneNumber":"xxxxxxxxxx",
"email":xxxx,
"department":"xxxxx"
},
The "\\n" says to put a literal \n in the string - 2 chars. You should just use "\n" to say that its a new line - 1 char.
Note if viewing in Windows Notepad, \n is not enough for a new line.
A simple ' ' (space character) is enough to do what is needed, the json key does hold a string after all, if you need something more prominent you can use '\t', refer here for more.

Javascript Replace doesn't work because of Escape Sequence

I need to replace every '\n' in a var with a <br> tag but the code I tried doesn't work. Here's my example and code:
Example:
Hello there \n Are you online? \n What do you mean?
Should become:
Hello there <br> Are you online? <br> What do you mean?
Code:
var text = 'Hello there \n Are you online? \n What do you mean?';
var find = '\n';
var re = new RegExp(find, 'g');
re = text .replace(re, '<br>');
What am I doing wrong?
var text = 'Hello there \n Are you online? \n What do you mean?';
var find = '\n';
var re = new RegExp(find, 'g');
re = text.replace(re, '<br>');
document.write(re);
Works fine
Working Fiddle
In your fiddle (which you did not post in your original question) there are several issues addressed already in the comments. But the crux of your problem -- that would have helped us help you faster -- is that you're pulling a string with "\n" from an innerHTML property. Those are not newline characters, because if you're seeing a literal "\n" instead of a newline, it means it has been escaped. Therefore, you need to use "\\n" in your regular expression, not "\n". Use the devtool consoles in modern browsers to inspect your variables and catch errors.
Code:
var el = document.getElementById("ado")
var text = document.getElementById("ado").innerHTML;
text = text.replace(/\\n/g, '<br>');
el.innerHTML = text
in your fiddle you wrote :
document.findElementById
instead of
document.getElementById
I think it is one of things that should solve your issue !

JQuery detect newline in a string

A "str" variable in JavaScript return by a backend contains a string with a few paragraphs separated by line breakers.. When I do this:
console.log(str);
the Firefox console displays:
"This is paragraph 1.
This is paragraph2.
This is paragraph3"
The problem is, this str is NOT separated by a "\n" character. It's just separated by invisible linebreaks, as you can see in the console output. Is there any way to detect this line break? What I'm eventually trying to do is replace these invisible line breaks with a "br" tag so that I can append it inside the html document..
Is there a way to do this?
Thanks
(Unfortunately, there is no way to change the backend..)
Take a look at nl2br on php.js which seems exactly what you're looking for. Basically, it's:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
Demo : http://devilmaycode.altervista.org/jquery-convert-line-breaks-to-br-nl2br-equivalent/
var text = "This is paragraph 1.
This is paragraph2.
This is paragraph3";
var matches = text.match(/\n/g);
var new_lines = matches ? matches.length : 0; //Get no. of new line here
Demo
As an alternative thought (and if possible in your situation), because you essentially want to render the text in HTML with the line-breaks preserved, you can make use of CSS to do this for you. Take a look at the the white-space property with a value of pre-line or pre-wrap:
Sequences of whitespace will collapse into a single whitespace. Text will wrap when necessary, and on line breaks -
W3Schools
So, if you append the string to the DOM as a paragraph like:
<p class="preserveLineBreaks">This is paragraph 1.
This is paragraph2.
This is paragraph3<p>
Then with a simple CSS selector as follows, you'll get the expected result:
.preserveLineBreaks {
white-space: pre-line; //or pre-wrap
}
Actually, the "invisible line breaks" in the Firefox console are the \n characters. I've included a line to confirm this in the code below. In addition, browsers will generally ignore the \n character in favor of the <br/> and so the str variable that you have should display nicely as one line. To however identify the "\n" chars and replace them with <br />, try this
<span id="someText">This is
some text
that I need
to modify
</span>
<script>
var text = document.getElementById("someText") ;
alert(text.innerHTML.match(/\n/g).length) ; // confirm \n are in var
alert (text.innerHTML) ;
var withBRs = text.innerHTML.replace(/\n/g, "<br />") ;
text.innerHTML = withBRs ;
</script>

to replace " " with

this is my javascript code:
mystring = "this is sample";
nestring = mystring.replace(/ /g," ");
I need nestring ouput "this is sample".
but with the code above, nestring = "this is sample"
how can I replace space( ) with &nbsp( )?
Many thanks!
re:
I embed svg in html. But ie, chrome do not support xml:space=preserve, firefox does. By replace " " with &nbsp, multiple " " will not condense to one " ".
You could use the Unicode:
nestring = mystring.replace(/ /g, "\u00a0");
But your example did exactly what you told it to.
If you want to replace the characters with character code 32 (0x20) with character with character code 160 (0xA0), you can use the fromCharCode method to create the string to replace with:
nestring = mystring.replace(/ /g, String.fromCharCode(160));
Your code works fine, but if you are writing the result to the document you will only see the spaces because they are HTML encoded.
If you alert(nestring); you will see that the spaces are replaced.

Categories

Resources