简体   繁体   English

在JavaScript中将字符串中每个单词的首字母转换为大写

[英]Convert first letter of each word in a string to Uppercase in JavaScript

I can write this code in a simpler way but I want to write it as a function based code. 我可以以更简单的方式编写此代码,但我想将其编写为基于函数的代码。 I am looking to change the starting letter of each word in a string to uppercase.Please help!! 我想将字符串中每个单词的开头字母更改为大写。请帮忙!

  function convertuc(str) {

  let arr = str.toLowerCase().split(" ");

  for (let s of arr){
  let arr2 = arr.map(s.charAt(0).toUpperCase() + s.substring(1)).join(" ");
   }
  return arr2
  };

  console.log(convertuc("convert the first letter to upper case")); // Test//

What about to use pure CSS? 如何使用纯CSS?

 p { text-transform: capitalize; } 
 <p>this is a simple sentence.</p> 

You're almost there. 你快到了。 You don't need a for loop since you're already using map (which does the iteration for you and builds a new array by transforming each string in arr to a new one based on the function provided). 您不需要for循环,因为您已经在使用map (它会为您进行迭代,并根据提供的函数将arr中的每个字符串转换为新的字符串,从而构建一个新的数组)。

 function convertuc(str) { let arr = str.toLowerCase().split(" "); let arr2 = arr.map(s => s.charAt(0).toUpperCase() + s.substring(1)).join(" "); return arr2; // note that arr2 is a string now because of .join(" ") }; console.log(convertuc("convert the first letter to upper case")); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 正则表达式模式,用于检查字符串中每个单词的第一个字母,如果它是Javascript中的大写字母 - Regex Pattern for checking the first letter of each word in a string if its Uppercase in Javascript 在 JavaScript 中获取字符串中每个单词的首字母 - Get first letter of each word in a string, in JavaScript 将包含变音符号的单词中的第一个字母转换为大写 - Convert first letter to uppercase in word containing diacritics 在JS中将每个单词的第一个字母转换为大写 - Convert first letter of every word to uppercase in JS 给定一个字符串数组,将每个字符串转换为: 如果第一个字母大写则大写 如果第一个字母小写则小写 - Given an array of strings, convert each string into: uppercase if first letter is capital lower case if first letter is small 在JavaScript中将字符串中的第一个字母更改为大写 - Change first letter in string to uppercase in JavaScript JavaScript:如何返回字符串中每个单词的首字母 - JavaScript: how to return the first letter of each word in a string Javascript错误返回提供的字符串,每个单词的首字母大写 - Javascript error with Returning the provided string with the first letter of each word capitalized Javascript使用循环返回字符串中每个单词的第一个字母的位置 - Javascript Return the location of the first letter of each word in a string using a loop 只有当lengh> 2时,Javascript才会将字符串中每个单词的首字母大写 - Javascript capitalize first letter of each word in a string only if lengh > 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM