如何将第一个单词的第一个字符转换为大写?

时间:2019-05-16 08:31:15

标签: javascript html string

我想要这个: 示例:stackoverflow是有帮助的。 => Stackoverflow非常有用。

作为示例,节目希望将我的第一个单词的第一个字符转换为大写。 我尝试了下面给出的代码,该代码无法正常工作,不了解我在做什么错,请帮忙。

<textarea autocomplete="off" cols="30" id="TextInput" name="message" oninput="myFunction()" rows="10" style="width: 100%;"></textarea>

<input id="FistWordFirstCharcterCapital" onclick="FistWordFirstCharcterCapital()" style="color: black;" type="button" value="First word first character capital!" /> </br>
</br>

<script>
  function FistWordFirstCharcterCapital() {
    var x = document.getElementById("TextInput").value.replace(string[0], string[0].toUpperCase());
    document.getElementById("TextInput").value = x;
  }
</script>

5 个答案:

答案 0 :(得分:3)

将其像数组对象一样处理,以获取第一个字符,将其大写,然后concat至字符串的其余部分:

const str = "hello World!";
const upper = ([c, ...r]) => c.toUpperCase().concat(...r);
console.log(upper(str));

答案 1 :(得分:0)

您可以使用charAt来获取第一个字母:

const string = "stackoverflow is helpful."
const capitalizedString = string.charAt(0).toUpperCase() + string.slice(1)

console.log(capitalizedString)

答案 2 :(得分:0)

您既不想使用replace,也不想使用string[0]之类的东西。相反,请使用下面的小方法

const s = 'foo bar baz';

function ucFirst(str) {
  return str.substr(0, 1).toUpperCase() + str.substr(1);
}

console.log(ucFirst(s));

答案 3 :(得分:0)

只需使用此方法

function jsUcfirst(string) 
{
    return string.charAt(0).toUpperCase() + string.slice(1);
}

答案 4 :(得分:0)

由于您似乎开始使用JS,因此这里有一个详细的示例:

function FistWordFirstCharcterCapital() {
  let text =  document.getElementById("TextInput").value;
  let firstSpaceIndex = text.indexOf(" ")!=-1 ? text.indexOf(" ")+1:text.length;
  let firstWord = text.substr(0, firstSpaceIndex);
  let firstWordUpper = firstWord.charAt(0).toUpperCase() + firstWord.slice(1)
  document.getElementById("TextInput").value = firstWordUpper + text.substr(firstSpaceIndex);;
}
<textarea autocomplete="off" cols="30" id="TextInput" name="message" rows="10" style="width: 100%;">
</textarea>

<input id="FistWordFirstCharcterCapital" onclick="FistWordFirstCharcterCapital()" style="color: black;" type="button" value="First word first character capital!" />

相关问题