简体   繁体   中英

split('\n') doesn't work in the browser but works in jsbin

I'm writing the code that is supposed to parse the text. The first step is to split it into array of lines. I do it with: let lines = input.split('\\n'); Function I wrote works perfectly when tested in jsbin but it doesn't work when tested in the browser. In the browser input is passed from the text input to the component but when logged into console looks fine. What might be the case?

input: '\\\\page 1 \\n\\ page 1.1'

Code:

function parseTree(input) {
  if (input === '') {
    return '';
  }
  console.log(input)
  let root = {title: null, isRoot: true, children: [] };
  let lines = input.split('\n');
  console.log(lines);
  /* ... */
  return root;
}

parseTree('\\page 1 \n\ page 1.1');

in jsbin the result is (first line is input, second lines array):

"\\page 1 page 1.1"

["\\page 1 ", " page 1.1"]

( https://jsbin.com/yacuhot/edit?js,console )

while in browser console it's:

\\page 1 \\n\\ page 1.1

["\\page 1 \\n\\ page 1.1"]

text from input containing \\n is not line break , it has no special meaning ..

consider it as escaped version of it and hence your split will not work on it.

as it is escaped split('\\\\n') should work but thats not what you want.

to have true new line in your input you want to use textarea element instead

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