打印字符串的后半部分

时间:2018-04-27 00:39:36

标签: javascript string

您好我正在努力通过使用读取线同步来学习npm。我仍然是javascript的新手,我正在尝试将故事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)}"`);

1 个答案:

答案 0 :(得分:1)

你可以使用javascript的子串函数,将字符串长度除以2作为起始位置。

var x = "hello there!"
console.log(x.substring(x.length / 2))  // there!