2

I was learning 去哪儿网-2017笔试题 and programing. In my program, I want to use readline() function to read a single line from input from stdin. I know that readline() function belongs to JavaScript Shell according to MDN. But the function is not defined when I run the code in my browser.

var line;
while (line = read_line()) {
  while (line.indexOf(" ") != -1) {
    line = line.replace(" ", "");
  }
  if (line.length <= 6) {
    print(line);
  } else if (line.length > 6 && line.length <= 14) {
    var line1 = line.substring(0, 6);
    var line2 = line.substring(6);
    print(line1 + " " + line2);
  } else if (line.length > 14 && line.length <= 18) {
    var line1 = line.substring(0, 6);
    var line2 = line.substring(6, 14);
    var line3 = line.substring(14);
    print(line1 + " " + line2 + " " + line3);
  }
}

If I want to run the code in my browser. What should I do?

Thank you very much.

antzshrek
  • 9,276
  • 5
  • 26
  • 43
lbs0912
  • 331
  • 1
  • 3
  • 13
  • 3
    From where are you expecting to read? You do not have a file. Browser based JS does not have stdin - or are you talking node.js? – mplungjan Mar 10 '17 at 15:27
  • You can't read from stdin in javascript – Dave Clough Mar 10 '17 at 15:28
  • 1
    It's for the js shell *command line* program which has nothing to do with js within a web browser. Where would it even read from? – Alex K. Mar 10 '17 at 15:28
  • 2
    The function, and the mdn page you link to, are about writing programs for the *JavaScript shell*, `jsc`. You can't run it in a browser. – Jared Smith Mar 10 '17 at 15:29
  • 1
    @mplungjan its `jsc`. Predates (and largely superceded by) node. – Jared Smith Mar 10 '17 at 15:31
  • You could just take the input and then use "string.split('\n')" to get the lines into an array and then store it in a variable for example "lines" then to get the line you want just call "lines[0]" where "0" can be replaced with any line number. – Sam lemonts May 17 '18 at 17:19
  • For this question, this link might be helpful https://stackoverflow.com/questions/5396020/is-there-a-way-to-read-standard-input-with-javascript – TechieViking Jan 10 '19 at 20:59

1 Answers1

1

As you mentioned above and the documentation says Introduction to the JavaScript shell

it is a command line options and you have to run that over the command shell. Also, you can check SpiderMonkey to have a better understanding.