根据用户对CharAt的选择,如何添加句子的其余部分?

时间:2017-01-10 00:51:38

标签: javascript arrays string split

我有这个简单的功能,用户可以输入一个句子,并根据用户的选择来资助一个字母。例如,如果用户选择将首字母大写为句子“嘿”,他会写titleCase("hey", 0)但它只返回那个大写字母而不是整个“嘿”字。这是因为我把它分成了数组,但是我怎样才能返回整个单词,而不仅仅是大写单词呢?我的代码

function titleCase(str, userChoice) {
var string = str;
var split = string.split(" ");
for (i = 0; i < split.length; i++) {
split[i] = split[i].charAt(userChoice).toUpperCase(); + split[i].slice(0);
}
console.log (split.join(" "));
}

titleCase();

2 个答案:

答案 0 :(得分:3)

这个怎么样?

只需将所选索引用户大写,然后返回字符串。

function titleCase(str, userChoice) {
  var string = str;
  var split = string.split("");

  split[userChoice] = split[userChoice].toUpperCase();
  return (split.join(''));
}

console.log(titleCase('hey', 0))

我在你的代码中注意到的问题:

string.split(" "); - &gt;这将在空格处分割字符串,但你的字符串是一个单词,所以它永远不会被拆分。

答案 1 :(得分:0)

function titleCase(str, userChoice) {
  var str = str;
  var split = str.split(" ");
  split[userChoice] = capitalize(split[userChoice]);
  return split.join(" ");
}

function capitalize(s) {
  return s[0].toUpperCase() + s.substr(1, s.length - 1)
}

console.log(titleCase('hello world', 0));
console.log(titleCase('hello world', 1));