Newline \n problem in JS - javascript

I am reading a file with xmlHttp object and splitting the responseText with newlines by split method.
But "\n" character literally doesn't work. It acts like an error in my code and causes my code not even function.
Here is the line:
var lines=myPlaylist.responseText.split("\n");
There is no error if I split the array myPlaylist with other characters.
Just \n causes problem which I fail to understand.
At first, I thought the error was due to white-space:nowrap since I execute my code on Chrome.
Though I never used white-space in anywhere, I tried to set it to normal but it didn't work.
Similarly, I tried my code on other browsers (Firefox, IE etc), it didn't work either. Looks like I have a problem with using \n. Is there any other way to use newline or error with my code?
And by the way, error seems to be a syntax error since it does not just ignore \n character. Simply causes my code not to work
EDIT: An example responseText
[playlist]
File1=http://localhost:7000/Videos/Big%20Buck%20Bunny%20Trailer.ogv
Title1=Bunny Trailer
Length1=23
File2=http://localhost:7000/Videos/Dizzy%20Cat%20Video.ogv
Title2=Kedi
Length2=33
NumberOfEntries=2
Version=2

I found my own solution to my problem.
After using random special characters, \r character used for carriage return worked like a charm for my problem.
It acted like a newline \n character or at least it did its job in my case.
Thanks everyone for answers and helpful comments.

Try using this line
/\n/
Instead of this one
"\n"

Here's an SO thread that will provide a bit more insight
JavaScript string newline character?
EDIT1:
I just tested this and it splits appropriately on new lines. Can you post some of what you're trying to split?
<html>
<script>
function testSplit(value)
{
var lines = value.split(/\n/);
alert(lines);
}
</script>
<body>
<textarea id="test" name="test" onblur="testSplit(this.value);">
</textarea>
</body>
</html>
EDIT2:
Can you try converting your responseText to an object and seeing what you get from it - sorry, just shooting from the hip here since I haven't had time to mock up anything for testing.
eval("var playlistResponse = ("+ myPlaylist.responseText +")");
Here's a somewhat old article that might be useful to you: http://www.peachpit.com/articles/article.aspx?p=443580&seqNum=4

Use \\n instead of \n i tried on my code and it is working fine

This should work without problem.
Are you certain that myPlaylist has a responseText property, and that property is a string?
What happens if you catch an eventual error?
try {
var lines = myPlaylist.responseText.split(/\n/g);
alert(lines.length);
} catch (e) {
alert(e.message);
}

Related

Illegal character in javascript

I've been debugging this for hours already but really can't find the culprit of this illegal character. My javascript looks fine. This is my code.
this.PrintApplication = function Test$PrintApplication(ApplicationID, callback) {
$.post("/Application/PrintApplication/" + ApplicationID,
function (data) {
var result = eval(data);
if (result.error) {
DisplayPrompt("Error", result.message);
return;
}
else {
callback(result.data);
}
});
};
In firebug it shows.
In inspect in chrome and in console it redirects me in this line.
Any idea where is that illegal character is in my function?
It looks like you've got some unprintable characters in your source. Do you have a way of displaying those in your editor and deleting them? Deleting and retyping the line might fix it as well.
If that's not the case, maybe what you're trying to evaluate isn't JavaScript at all. You could be running that on an image or some kind of binary data.
Remember to be extra super careful when using eval on data that comes from an external source. If you can avoid doing it, avoid it.
This might be due to the reason that you have copied the code from web and simply pasted in your file. Try typing the same code to the file.
This error occurs due to UTF-8 characters.
This could happen if you normally type with different alphabets. For example the Γreek question mark ; is a different ASCII character from the English semi colon ;. If you use the first, you'll get exactly this error.
One solution is to copy paste your method to notepad and then back to your IDE.
This will often normalise and eliminate weird characters that might be hidden or undecipherable.

JSON.parse() wont accept valid JSON

I am trying to parse the following string: {"text":"Hej"}, in JS
This is valid JSON. It's a property on an object. But when I try to parse it, I get the following error:
Why does this happen?
Simple.. your string isn't valid (for JSON): it contains a control character at position 13.
Have a look for yourself: json_str.charCodeAt(13) and compare with http://en.wikipedia.org/wiki/C0_and_C1_control_codes .
Edit: seems like you had a Line Feed = (LF) = \n in there.
Oh I got it now!
It was a line break, as you can see here:
I will replace line breaks with <br />
Thank so much everybody for the help!
For any future members also getting the issue, here's my problem in depth and how to possibly fix it.
I allowed users to write whatever they wanted in a textarea, and that would be via AJAX inserted into my statuses MySQL table, without escaping any characters like \n or others. This is bad practice and may lead to issues like this.
How to fix it then..
Best practice is to escape it PHP. And it couldn't be simpler, just use the built-in PHP function: nl2br. This will replace all linebreaks with <br />. Here's an example:
$str = "Bar bar ba r foo foo foof foo bar
bar bar bar fooo
more foo foofo bar foo bar";
$new_string = nl2br($str);
If you are a little late to the party, and only realizing this issue a little to late, you can do it in JavaScript too! Like so:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
Just remeber to this before parsing JSON or anything like that. As JSON will error.
Hope it helped you, happy developing!!

Wordpress & Javascript: String variable having html tags being read by browser with newline character

I have gone crazy trying to resolve this issue.
In my javascript code I have am defining a string variable in which I am putting an HTML table in the form of string.. i.e.:
var tData="<table><tbody><tr><a><th>Type</th><th>Score</th><th>Percentile</th></a></tr><tr><td><a>Overall</a></td><td>2.4</td><td>50%</td></tr><tr><td><a>Best 100</a></td><td>2.3</td><td>70%</td></tr></tbody></table>";
Now this variable assignment through the string is being read by my browser (both chrome and firefox) as an HTML code with line breaks. Take a look at the image below for more clarity.
The code works fine if I remove html tags and write a simple string. So I can assure you there are no previous inverted comma errors (i checked them multiple times) and no bogus characters.
I have spent too many hours on this issue. Please please help me on this.
EDIT
Added Wordpress in title and Tags as this is a wordpress issue.
Since your document is XHTML, you have to enclose your code into a CDATA section:
<script>
<![CDATA[
// code here
]]>
</script>
This prevents the browser from interpreting <...> sequences in the content as tags.
If you want multiline strings in JavaScript, you have to unescape the newline, ie
var str = "abc\
de";
Ok. Eureka!!!
I found a get around. I broke the following string :
var tData="<table><tbody><tr><a><th>Type</th><th>Score</th><th>Percentile</th></a></tr><tr><td><a>Overall</a></td><td>2.4</td><td>50%</td></tr><tr><td><a>Best 100</a></td><td>2.3</td><td>70%</td></tr></tbody></table>";
into
var tData = "<tab"+"le><tb"+"ody><t"+"r><a><t"+"h>Type</t"+"h><t"+"h>Score</t"+"h><t"+"h>Percentile</t"+"h></a></t"+"r><t"+"r><t"+"d><a>Overall</a></t"+"d><t"+"d>2.4</t"+"d><t"+"d>50%</t"+"d></t"+"r><t"+"r><t"+"d><a>Best 100</a></t"+"d><t"+"d>2.3</t"+"d><t"+"d>70%</t"+"d></t"+"r></tbo"+"dy></ta"+"ble>";
to fool the browser. I am still hoping for a better answer please.
Delete all invisible characters (whitespace) around that area,
then give it another try.
Try this:
var tData="<table><tbody>";
tData+="<tr><th><a>Type</a></th><th>Score</th><th>Percentile</th></tr>";
tData+="<tr><td><a>Overall</a></td><td>2.4</td><td>50%</td></tr>";
tData+="<tr><td><a>Best 100</a></td><td>2.3</td><td>70%</td></tr>";
tData+="</tbody></table>";
Possible Duplicate No visible cause for "Unexpected token ILLEGAL"

Dynamically insert special character into document title

I am trying to update the document.title with Javascript. This works fine, but now I want to insert the ü character into the title, which gives me a question mark at the place where the ü is supposed to be.
Here is my code (I omitted the rest of the title for clarity):
document.title = '\u2019 - \u252';
The strange thing is that the \u2019 part does work and gives me a quote, as expected. My charset is UTF-8, by the way.
What am I doing wrong here?
Do you want document.title = '\u00FC'; ? the &# and \u numbers are different in many places, or so i've found in my usages.
What's \u252? It doesn't seem to be a valid unicode escape, try \u0252?
Update: Apologies. I read it wrong. Thought you were looking for "ɒ" which is the result I get...
This worked for me on Chrome, Firefox and Safari (OSX)
document.title = '\u0252';

Javascript: replacing newlines with <br/> working in FF and SAFARI and not working in IE

Code in the post has been modified.
I was thinking that replacing \n with with javascript was quite a simple task, but it seems not to be so. Posts in Ask Ben or StackOverflow suggest that something as simple as:
var myRe = new RegExp(/\r?\n/g); // to avoid the re literal caching problem
lDes = $("div.descr").html();
lDes = lDes.replace (myRe, "<br/>");
lDes = lDes.replace (/(http:\/\/\S+)/g, "<a target=\"blank\" href=\"$1\">$1</a>");
$("div.descr").html(lDes);
will get the job done. Indeed, this work in FF and Safari but not in IE.
Or, using postie (great hint!)
Text has been created in a textarea and then stored in a database, then retrieved without further processing. It works using FF on windows and Safari on Mac. IE on windows, nada. Is it a major bug in my head? Is it a JQuery issue?
Have some idea about how to solve this? And possible reason for?
Many thanks
Instead of putting the text in question into a <div> on the page, perhaps you can put it directly into a block of Javascript. Now that will require that you have some server-side code to "protect" the Javascript string constant syntax, which is a strangely rare facility but easy to create. You just have to make sure that quote characters, as well as control characters and characters outside the 7-bit range, are appropriately "escaped" the way Javascript expects string constants to look.
Here's what it'd look like in one of my applications. This is a Java/JSP example, so probably not what you're using, and of course the "escape" function I call is my own invention, but just so you see what I mean:
var theText = '${pointy:escapeJS(data.theText)}';
$('#target').html(theText.replace(/\n/g, '<br>'));
Of course if you're receiving the text as an AJAX response, things are simpler.
Now that example leaves out something important: you have to make sure the text is HTML-escaped before dropping it into the document. Perhaps that's been done server-side, or if not you can do that in Javascript too:
$('#target').html(theText
.replace(/\r/g, '') // get rid of carriage returns
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\n\n/g, '\n \n')
.replace(/\n/g, '<br>')
);
(There are better/faster ways to do HTML escaping of course; that's just an example.) Note that I stick explicit blank padding between successive newlines - that's something I cribbed from some code I have and I think I did that because successive <br> elements without intervening "stuff" might not give multiple blank lines in the result; not sure however.
What DOCTYPE are you using? It may be that, depending on the DOCTYPE (i.e., not using XHTML), <BR/> should be rendered as <BR>. IE could be in some weird state of compatibility or quirks mode, etc.

Categories

Resources