开发者

Newline \n problem in JS

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜