Strange String.split("\n") behavior
I have a .txt text file, containing some lines.. I load the contain using the RequestBuilder object, and split the responseText with words = String.split("\n"); but i wonder, why the result is contains the "\n" part.. For example, my text:
abc
def
ghi
the result is,
words[0] = "abc\n"
words[1] = "def\n"
words[2] = "ghi\n"
Any help is highly appreciat开发者_如何学JAVAed. Thanks in advance.
Try using string.split("\\n+")
. Or even better - split("[\\r\\n]+")
You may also want to consider String[] lines = text.split("\\\\n");
Windows carriage returns ("\r\n"
) shouldn't make a visible difference to your results, nor should you need to escape the regular expression you pass to String.split()
.
Here's proof of both the above using str.split("\n")
: http://ideone.com/4PnZi
If you do have Windows carriage returns though, you should (although strictly not necessary) use str.split("\r\n")
: http://ideone.com/XcF3C
If split uses regex you should use "\\n" instead of "\n"
Try using string.split("\\\\n")
. It works for me.
Maybe it's trivial, but the .split method is sensitive to spaces and text breaks. If we don't know how the original text is written, we have to consider that this could make some differences (single line, breaks, multilines, etc).
Single line text:
const inlineText = "Hello world!";
console.log(inlineText.split(' ')) //['Hello', 'world!']
Multi lines text:
const multilinesText = `
Hello world!
`
console.log(multilinesText.split(' ')) // ['\nHello', 'world!', '\n']
精彩评论