javascript Title_case_sentence

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Title_case_sentence相关的知识,希望对你有一定的参考价值。


/*---------------------------------------------BASIC-------------------------------------------------------*/

function titleCase(str) {
var strPrepare = str.toLowerCase().split(" "); /*готовим стринг к апперкейсу, занижая все под ловеркейс. 
Сначала переводим в ловеркейс, потому, что сплит превращает стринг в еррей,а ловеркейс на ерреях не работает*/

   
   
   var result = strPrepare.map(function(val){
  
  return val.replace(val.charAt(0), val.charAt(0).toUpperCase());//меппим, заменяем первую букву на нее же в апперкейсе
},0);
  
  return result.join(" ");

}

titleCase("I'm a little tea pot");


/*---------------------------------------Advanced Code Solution-------------------------------------------*/

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}
:rocket: Run Code299

Code Explanation:
The solution works by first lowercasing all the characters in the string and then only uppercasing the first character of each word.

Lowercase the whole string using str.toLowerCase().

Replace every word’s first character to uppercase using .replace.

Search for character at the beginning of each word i.e. matching any character following a space or matching the first character of the whole string, by using the following pattern.

Regex explanation:

Find all non-whitespace characters (\S)
At the beginning of string (^)
Or after any whitespace character (\s)
The g modifier searches for other such word pattern in the whole string and replaces them.

以上是关于javascript Title_case_sentence的主要内容,如果未能解决你的问题,请参考以下文章

javascript JavaScript isset()等效: - JavaScript

JavaScript 使用JavaScript更改CSS(JavaScript)

JavaScript之基础-1 JavaScript(概述基础语法)

前端基础-JavaScript的基本概述和语法

JavaScript

JavaScript