javascript - 打印字符串的后半部分

标签 javascript string

您好,我正在尝试通过阅读行同步来学习 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/

相关文章:

python - 如何在 Python 中找到带有字符串列表的预先存在的变量?

javascript - Chrome 使用 Lightbox 调用服务器两次

php - CronJobs 可以执行包含 Javascript 的 php 吗?如果否,还有其他选择吗?

javascript - toggleClass 不适用于特定 div

c# - 在 C# 中下载一个 JSON 字符串

python - 为什么 MySQL 连接查询的输出作为嵌套列表项返回?

javascript - 在 GraphQL 中是否可以在对象类型级别上使用解析器?

javascript - Angular-redux 设计 - 数组选择器

ios - 将 Swift 字符串转换为数组

c++ - 反转字符数组中单词的顺序