您好,我正在尝试通过阅读行同步来学习 npm。我对 javascript 还是很陌生,我正在尝试获取 story var 并只打印出字符串的后半部分。我想也许我可以用切片来做,但我不知道如何让它打印出后半部分。
我也想也许我可以写一个函数,但我还是不确定如何在不对索引进行硬编码的情况下获得所输入内容的后半部分。哦,我可以在读取行同步中写入函数吗?谢谢您的帮助。
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的substring函数,将字符串长度除以2作为起始位置。
var x = "hello there!"
console.log(x.substring(x.length / 2)) // there!
关于javascript - 打印字符串的后半部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053685/