简体   繁体   中英

Is “\n” not working in string.split for JavaScript?

I have a external resource (raw text file) like:

1. Title 1
Content 1
|
2. Title 2
Content 2
|
3. Title 3
Content 3

I load them in a web page via AJAX and want to use content.split("\\n|\\n") to extract its content into an array for my use. But it seems it's not working.

What's weird is that split("\\n|") works, but neither do split("|\\n") nor split("\\n|\\n") work.

That's not JavaScript related. That's related to the operating system.

  var canonicalizeNewlines = function(str) {
      return str.replace(/(\r\n|\r|\n)/g, '\n');
  };

Basically DOS(Windows), FreeBSD and Unix systems use different white characters to end a line. /r is for DOS , /r/n is for FreeBSD based(Mac). This will enforce a single style for all your new lines, the Unix default style which is \\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