嗨,我正在尝试通过阅读行同步来学习npm。我对javascript还是很陌生,我正在尝试使用故事var并仅打印字符串的最后一半。我想过也许可以用slice来做,但是我不知道如何把它打印出来。
我还以为也许我可以编写一个函数,但我又不确定如何在不对索引进行硬编码的情况下获取所输入内容的最后一半。哦,我可以在读行同步中编写函数吗?谢谢您的帮助。
var readlineSync = require('readline-sync');
var firstNamer = readlineSync.question('Hi!, May I have your first
name?');
console.log("Hi " + firstNamer.toUpperCase() + "! \nIt's sooooo good to
see you");
var lastName = readlineSync.question("What's your last name?");
console.log(firstNamer.toUpperCase() + " " + lastName.toUpperCase() + "
Wow! such a cool name.");
var age = readlineSync.question(`Now that I know your name is
${firstNamer} ${lastName} \n can I get your age?`);
console.log(`WOW! \tNow I know that ${firstNamer.toUpperCase()}
${lastName.toUpperCase()} is ${age} and that's just great!`);
var story = readlineSync.question(`Well ${firstNamer} now that I know
your first and last name, tell me your story?`);
console.log(`So your telling me that that you ${story} hmmmm
interesting`)
var halfStory = readlineSync.question(`So now that I know your story I
can tell you that what you told me was ${story.length} characters long
\n I'll show the last half now. ok?`);
console.log(`\n this is the last half of your story "${story.slice(0,
story.length / 2)}"`);
最佳答案
您可以只使用javascript子字符串函数,将字符串长度除以2作为起始位置。
var x = "hello there!"
console.log(x.substring(x.length / 2)) // there!