How can I in Javascript read strings from a textfile and display them in an alert box with newlines?
Suppose I have an ASCII textfile "messages.txt" containing two lines:
AAA\nBBB\nCCC
DDD\nEEE\nFFF
In javascript, I read the file content and store it in a variable "m":
var m;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function ()
{ if ((xmlhttp.readyState==4) && (xmlhttp.status==200 || xmlhttp.status==0))
{ m = xmlhttp.responseText.split('\n'); };
};
xmlhttp.open("GET", "messages.txt", false);
xmlhttp.send(null);
Now when I display the first message with
console.log(m[0]);
alert(m[0]);
it is shown exactly as in the textfile and with no line breaks; i.e
AAA\nBBB\nCCC
and not as
AAA
BBB
CCC
Changing \n to \\n, \r\n, \\r\\n or %0D%0A in the textfile doesn't help; the alert is still displayed as one line including the escape characters without replacing them by newline. Changing the encoding of "messages.txt" from ASCII to UTF-8 didn't help either.
To clarify the problem:
When m is read from the file "message.txt", it is split into an array of strings. m[0] equal to "AAA\nBBB\nCCC".
console.log(m[0]); // displays AAA\nBBB\nCCC
console.log('AAA\nBBB\nCCC'); // displays AAA
// BBB
// CCC
console.log(typeof(m[0]) // displays string
console.log(m[0]=="AAA\nBBB\nCCC"); // displays false
Why is m[0] not equal to "AAA\nBBB\nCCC" (even if exactly this is what is displayed in the console)? I guess, that is the reason why no line breaks appear.
you need to add another \ at split('\n') to be split('\\n')
or change the single quote to douple quotes split("\n")
also i encourage you to read this quick article about 'Single' vs "Double" quotes
Single quotes don't interpret newline breaks (\n). So, you need to change the quotes in your split() method to have double quotes.
Use the split() function like so.
const str = "Hi! I'm text!\nIsn't this supposed to be newline?";
console.log(str.split("\n"));
This should return an array like so when run.
[
"Hi! I'm text!",
"Isn't this supposed to be newline?"
]
This is how to separate your text with line breaks.
For more information, see this other Stack Overflow question.
Related
So, I have the following code:
<script type="text/javascript">
var name = prompt("What's your name?");
var greeting = "Hello " + name + " :D";
console.log(greeting);
</script>
I am trying to break out from name variable. For example: answering the question by
"alert(1);\\
In browser console, printing name variable shows the following:
Now, when trying to create a second variable with the same content it produces an error.
Why does "name" contain invalid syntax content? and is there any way to break out from the variable in this scenario?
When you input "alert(1);\\ in the prompt, the special characters are automatically escaped and the input is assigned to name, but when you are doing that via the console or a script, you have to escape the characters manually. Since you wrote the string using double-quotes, the correct way to do the assignment would be:
var test = "\"alert(1);\\\\";
When uing single-quotes, you wouldn't have to escape the double-quotes:
var test = '"alert(1);\\\\';
What I did here is escape the required characters by putting a \ before them. What you see when you try to view the value of name is the actual content without the escaping.
JavaScript believes that you are ending the string literal at the second quotation mark.
Two possible solutions:
Wrap with single quotes: test = '"alert(1)\\'
Escape the second quote: test = "\"alert//"
So I am trying to figure out how I can remove a select set of characters on the end of a string. I've tried some general 'solutions' like str.replace or creating a rtrim, but I kept seeing some situation in which it wouldn't work.
Possible inputs might be:
\r\n some random text \r\n
\r\n some random text
some random text \r\n
some random text
Only the first and the third line should be affected by this function.
Basicly I'm looking for a rtrim function that takes as a parameter, the value/character set that should be trimmed.
I think it might be something way too obvious that I don't see, but at this point I feel like I could use some help.
You can use the following piece of code to do that for you:
var a = "\r\n some random text \r\n";
a = a.replace(new RegExp('\r\n$'), '');
Here, $ matches end of input.
You can refer to the regular expressions guide here to find out more about regex in JS.
EDIT:
If you really need a function for this:
var rTrimRegex = new RegExp('\r\n$');
var rTrim = function(input){
return input.replace(rTrimRegex, '');
}
And then use it inside your code maybe like:
var str = 'my name is foo\r\n\r\n';
str = rTrim(str);
I need to insert a Carriage Return in a String. As far as I know the \r should do it but here is the problem:
I wrote this in the browser console: 1\r2 then I get: 12 in return. Now I copy/paste it on Notepad++ https://imgur.com/a/pUW8p
There is a CR and a LF there. How I can add just a CR?
Note that you can replace the LF(\n) in notepad, save the file and the LFs are gone.
In ES6 with string templates you just introduce the carriage return as written text.
Also you can use \n to mark carriage return in quoted strings.
const str = `l
e`;
console.log(str);
const str2 = 'l\ne';
console.log(str2);
Usually, carriage returns often go like this...
\n
and you can use more than one to go down multiple lines.
It's the equivalent of pressing the enter/return key after you type one line and you want to move to the next one.
For example,
var astring = "This is a \n test";
print(astring);
You would get:
This is a
test
Hope it answers your question,
Alexander B.
I have this JSON string:
{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}
I can parse it when I do this:
pg = JSON.parse(myJSONString.replace(/\\/g, ""));
But when I access pg.text the value is:
Line 1nLine 2.
But I want the value to be exactly:
Line 1\nLine 2
The JSON string is valid in terms of the target program which interprets it as part of a larger command. It's Minecraft actually. Minecraft will render this as you would expect with Line 1 and Line 2 on separate lines.
But I'm making a editor that needs to read the \n back in as is. Which will be displayed in an html input field.
Just as some context here is the full command which contains some JSON code.
/summon zombie ~ ~1 ~ {HandItems:[{id:"minecraft:written_book",Count:1b,tag:{title:"",author:"",pages:["{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}"]}},{}]}
Try adding [1] at /\[1]/g but works for single slash only, but since the type of the quoted json i think is a string when you parse that it slash will automatically be removed so you don't even need to use replace. and \n will remain as.
var myString ='{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}';
console.log(JSON.parse(myString.replace(/\\[1]/g, ""))); //adding [1] will remove single slash \\n -> \n
var myString =JSON.parse(myString.replace(/\\[1]/g, ""));
console.log(myString.text);
Your string is not valid JSON, and ideally you should fix the code that generates it, or contact the provider of it.
If the issue is that there is always one backslash too many, then you could do this:
// Need to escape the backslashes in this string literal to get the actual input:
var myJSONString = '{\\"text\\":\\"Line 1\\\\nLine 2\\",\\"color\\":\\"black\\"}';
console.log(myJSONString);
// Only replace backslashes that are not preceded by another:
var fixedJSON = myJSONString.replace(/([^\\])\\/g, "$1");
console.log(fixedJSON);
var pg = JSON.parse(fixedJSON);
console.log(pg);
I am trying to replace line breaks with a comma in javascript but the code doesn't seem to work.
var data = "Series
Manga
Games
Artbooks
Visual Novels"
var output = data.replace(/(\r\n|\n|\r)/gm,",");
alert(output);
here you can see a online version http://jsfiddle.net/CBvpS/
Anyone know how to fix it?
Works great when your input string is syntactically correct:
var data = "Series\nManga\nGames\nArtbooks\nVisual Novels"
var output = data.replace(/\r?\n/gm,",");
alert(output);
http://jsfiddle.net/7V8rg/1/
Javascript does not have multi-line variables like php does, unless you manually escape(\) the end of the line. Further, this does not count as a line-break, so you would have to insert \ns to fix that as well. Otherwise, your code works fine, albeit with some minor modifications.
var data = "Series\n \
Manga\n \
Games\n \
Artbooks\n \
Visual Novels";
var output = data.replace(/(\r\n|\n|\r)/gm,",");
alert(output);
Take note, however, if your data is from example, an input text area, you do of course not need to worry about escaping the end of the line, and it will handle the data as it should.
JavaScript doesn't allow you to continue a string with new lines unless you add a backslash at the end of the line. For example:
var string = "a \
string is \
here";
With that being said, if you retrieved some text from a different source and wanted to replace the new lines, something like this should be all you need:
string = string.replace(/\n/g, ',');