简体   繁体   中英

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 appreciated. Thanks in advance.

Try using string.split("\\\\n+") . Or even better - split("[\\\\r\\\\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

您可能还需要考虑String[] lines = text.split("\\\\\\\\n");

如果split使用正则表达式,则应使用“ \\\\ n”而不是“ \\ 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM