Results 1 to 2 of 2
Feb 27, 2008, 09:09 #1
- Join Date
- Apr 2006
- 0 Post(s)
- 0 Thread(s)
Multiline strings and the .sort() method
Have a couple questions dealing with string literals and methods of the String core.
I have some preformatted text that is on multiple lines and I'm trying to manipulate it (for fun,
This is what I copied in my JS console (firebug/ff2/windows xp). I expanded the console so I can type
str = ' ONE TWO THREE';
wherever there's a newline, so in order to get it to not error I'd have to manually insert them like
str = '\ ONE\ TWO\ THREE';
str = 'ONE\nTWO\nTHREE';
It looks like example 1.3 is the same, except I'm manually typing the \n's inside of the string. My
only guess is that JS knows the difference and has different behavior with "fake" newlines (manually
typed \n's inside of quotes) and "real" newlines (the ones you dont see, but use the enter button on).
If I do...
str = '\ one\ two\ three\ '.split('\n');
However, if I do..
str = 'one\ntwo\nthree.split('\n');
So it must be something with real newlines vs manually typed newlines.
Also, Is there any reliable method to not having to terminate backslashes on multilines, while still
preserving the format?
one two three
alphabetically. So with this string input (1.6) I get this output (1.7). Now, this works perfectly if I do 'one\ntwo\nthree'.split('\n').sort() but as I've already mentioned it's in the format of 1.6.
['one', 'three', 'two']
Feb 27, 2008, 11:42 #2
- Join Date
- Jan 2007
- Christchurch, New Zealand
- 62 Post(s)
- 3 Thread(s)
When \n is used the string includes this as a standard character.
It's commonly used to split long lines of code, instead of text. When it's done on text it affects the contents of the string.
// str contains "This isa test of thebroadcastingsystem." str = 'This is\ a test of the\ broadcasting\ system.'; // str contains "This isa test of thebroadcastingsystem." str = 'This is \ a test of the \ broadcasting \ system.'; // str contains "This is a test of the broadcasting system." str = 'This is\ a test of the\ broadcasting\ system.'; // str contains "This is a test of the broadcasting system."
About the best you can manage is the following:
str = '\ This is a test.\n\ Here\'s another line.\n\ And the last line is here.\ '; // str contains "This is a test.\nHere's another line.\nAnd the last line is here."Programming Group Advisor
The 2013 SitePoint Awards - Nominate your heroes now!