利用JavaScript为句子加标题的3种方法示例

前言

本文基于Free Code Camp基本算法脚本“标题案例一句”。

在此算法中,我们要更改文本字符串,以便每个单词的开头始终都有一个大写字母。

在本文中,我将解释三种方法。首先使用FOR循环,其次使用map()方法,第三次使用replace()方法。

算法挑战

  • 返回提供的字符串,每个单词的首字母大写。确保单词的其余部分为小写。
  • 出于此练习的目的,你还应该大写连接词,例如“ the”和“ of”。

提供的测试用例

  • titleCase(“I'm a little tea pot”)返回一个字符串。
  • titleCase(“I'm a little tea pot”)返回“I'm A Little Tea Pot”。
  • titleCase(“sHoRt AnD sToUt”)返回“ Short And Stout”。
  • titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”)返回“Here Is My Handle Here Is My Spout”。

1.标题大小写带有FOR循环的句子

对于此解决方案,我们将使用String.prototype.toLowerCase()方法

String.prototype.split()方法,String.prototype.charAt()方法

String.prototype.slice()方法和Array.prototype.join()方法

  • toLowerCase()的方法返回主字符串值转换为小写
  • split()的方法通过分离串为子分割字符串对象到字符串数组。
  • charAt()的方法返回从字符串指定的字符。
  • slice()的方法提取的字符串的一部分,并返回一个新的字符串。
  • join()的方法连接到一个字符串数组的所有元素。

我们将需要在split()方法的括号之间添加一个空格

var strSplit = "I'm a little tea pot".split(' ');

它将输出一个由单词组成的数组:

var strSplit = ["I'm", "a", "little", "tea", "pot"];

如果不在括号中添加空格,则将得到以下输出:

var strSplit = ["I", "'", "m", " ", "a", " ", "l", "i", "t", "t", "l", "e", " ", "t", "e", "a", " ", "p", "o", "t"];

我们将其合并

str[i].charAt(0).toUpperCase()

在FOR循环中将大写前的字符串索引0字符

str[i].slice(1)

将从索引1提取到字符串的末尾。

为了标准化,我们将整个字符串设置为小写。

有注释:

function titleCase(str) {
 // Step 1. Lowercase the string
 str = str.toLowerCase();
 // str = "I'm a little tea pot".toLowerCase();
 // str = "i'm a little tea pot";

 // Step 2. Split the string into an array of strings
 str = str.split(' ');
 // str = "i'm a little tea pot".split(' ');
 // str = ["i'm", "a", "little", "tea", "pot"];

 // Step 3. Create the FOR loop
 for (var i = 0; i < str.length; i++) {
  str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
 /* Here str.length = 5
  1st iteration: str[0] = str[0].charAt(0).toUpperCase() + str[0].slice(1);
          str[0] = "i'm".charAt(0).toUpperCase() + "i'm".slice(1);
          str[0] = "I"              + "'m";
          str[0] = "I'm";
  2nd iteration: str[1] = str[1].charAt(0).toUpperCase() + str[1].slice(1);
          str[1] = "a".charAt(0).toUpperCase()  + "a".slice(1);
          str[1] = "A"              + "";
          str[1] = "A";
  3rd iteration: str[2] = str[2].charAt(0).toUpperCase()  + str[2].slice(1);
          str[2] = "little".charAt(0).toUpperCase() + "little".slice(1);
          str[2] = "L"               + "ittle";
          str[2] = "Little";
  4th iteration: str[3] = str[3].charAt(0).toUpperCase() + str[3].slice(1);
          str[3] = "tea".charAt(0).toUpperCase() + "tea".slice(1);
          str[3] = "T"              + "ea";
          str[3] = "Tea";
  5th iteration: str[4] = str[4].charAt(0).toUpperCase() + str[4].slice(1);
          str[4] = "pot".charAt(0).toUpperCase() + "pot".slice(1);
          str[4] = "P"              + "ot";
          str[4] = "Pot";
  End of the FOR Loop*/
 }

 // Step 4. Return the output
 return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}

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

没有注释:

function titleCase(str) {
 str = str.toLowerCase().split(' ');
 for (var i = 0; i < str.length; i++) {
  str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
 }
 return str.join(' ');
}
titleCase("I'm a little tea pot");

2.使用map()方法对案例进行标题案例

对于此解决方案,我们将使用Array.prototype.map()方法。

  • map()的方法创建调用此阵列中的每个元件上的提供功能的结果的新的数组。使用map会依次为数组中的每个元素调用一次提供的回调函数,并根据结果构造一个新的数组。

如上例所示,在应用map()方法之前,我们将小写并分割字符串。

代替使用FOR循环,我们将把map()方法作为条件与上一个示例的连接相同。

(word.charAt(0).toUpperCase() + word.slice(1));

有注释:

function titleCase(str) {
 // Step 1. Lowercase the string
 str = str.toLowerCase() // str = "i'm a little tea pot";

 // Step 2. Split the string into an array of strings
      .split(' ') // str = ["i'm", "a", "little", "tea", "pot"];

 // Step 3. Map over the array
      .map(function(word) {
  return (word.charAt(0).toUpperCase() + word.slice(1));
  /* Map process
  1st word: "i'm"  => (word.charAt(0).toUpperCase() + word.slice(1));
             "i'm".charAt(0).toUpperCase() + "i'm".slice(1);
                "I"           +   "'m";
             return "I'm";
  2nd word: "a"   => (word.charAt(0).toUpperCase() + word.slice(1));
             "a".charAt(0).toUpperCase()  + "".slice(1);
                "A"           +   "";
             return "A";
  3rd word: "little" => (word.charAt(0).toUpperCase()  + word.slice(1));
             "little".charAt(0).toUpperCase() + "little".slice(1);
                "L"            +   "ittle";
             return "Little";
  4th word: "tea"  => (word.charAt(0).toUpperCase() + word.slice(1));
             "tea".charAt(0).toUpperCase() + "tea".slice(1);
                "T"           +   "ea";
             return "Tea";
  5th word: "pot"  => (word.charAt(0).toUpperCase() + word.slice(1));
             "pot".charAt(0).toUpperCase() + "pot".slice(1);
                "P"           +   "ot";
             return "Pot";
  End of the map() method */
});

 // Step 4. Return the output
 return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}

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

没有注释:

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(word) {
  return (word.charAt(0).toUpperCase() + word.slice(1));
 }).join(' ');
}
titleCase("I'm a little tea pot");

3.使用map()和replace()方法对句子进行标题处理

对于此解决方案,我们将继续使用Array.prototype.map()方法并添加String.prototype.replace()方法。

replace()的方法返回与一些或通过替换替换的图案的所有比赛的新字符串。

在我们的例子中,replace()方法的模式将是一个字符串,该字符串将被新的替换替换,并将被视为逐字字符串。我们还可以使用正则表达式作为模式来解决此算法。

如将在第一个示例中看到的那样,在应用map()方法之前,我们将小写并拆分字符串。

有注释:

function titleCase(str) {
 // Step 1. Lowercase the string
 str = str.toLowerCase() // str = "i'm a little tea pot";

 // Step 2. Split the string into an array of strings
      .split(' ') // str = ["i'm", "a", "little", "tea", "pot"];

 // Step 3. Map over the array
      .map(function(word) {
  return word.replace(word[0], word[0].toUpperCase());
  /* Map process
  1st word: "i'm" => word.replace(word[0], word[0].toUpperCase());
            "i'm".replace("i", "I");
            return word => "I'm"
  2nd word: "a" => word.replace(word[0], word[0].toUpperCase());
           "a".replace("a", "A");
           return word => "A"
  3rd word: "little" => word.replace(word[0], word[0].toUpperCase());
             "little".replace("l", "L");
             return word => "Little"
  4th word: "tea" => word.replace(word[0], word[0].toUpperCase());
            "tea".replace("t", "T");
            return word => "Tea"
  5th word: "pot" => word.replace(word[0], word[0].toUpperCase());
            "pot".replace("p", "P");
            return word => "Pot"
  End of the map() method */
});

 // Step 4. Return the output
 return str.join(' '); // ["I'm", "A", "Little", "Tea", "Pot"].join(' ') => "I'm A Little Tea Pot"
}

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

没有注释:

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(word) {
  return word.replace(word[0], word[0].toUpperCase());
 }).join(' ');
}
titleCase("I'm a little tea pot");

总结

到此这篇关于利用JavaScript为句子加标题的文章就介绍到这了,更多相关JavaScript为句子加标题内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • JavaScript获取当前网页标题(title)的方法

    本文实例讲述了JavaScript获取当前网页标题(title)的方法.分享给大家供大家参考.具体如下: JS中的document.title可以获取当前网页的标题 <!DOCTYPE html> <html> <head> <title>jb51.net</title> </head> <body> current document's title is: <script> document.write(do

  • JS动态改变浏览器标题的方法

    本文实例讲述了JS动态改变浏览器标题的方法.分享给大家供大家参考,具体如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <hea

  • javascript 获取网页标题

    www.jb51.net测试 kdocTitle = document.title;//标题 if(kdocTitle == null){ var t_titles = document.getElementByTagName("title") if(t_titles && t_titles.length >0) { kdocTitle = t_titles[0]; }else{ kdocTitle = ""; } } window.alert

  • 一个JS函数搞定网页标题(title)闪动效果

    复制代码 代码如下: <html><head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title></head><body><script language="JavaScript"> step=0 function fla

  • javascript修改浏览器title方法 JS动态修改浏览器标题

    title在html中属于特殊的节点元素.因为它可以使用document.getElementsByTagName("title")[0]来获取网页的title标签,但却无法用document.getElementsByTagName("title")[0].innerHtml用更改它的值.经测试原生js有两种方式可以修改,jQuery中也能简单设置.不清楚的小伙伴们可以了解一下. innerText 方式 通过console.log(document.getEle

  • 利用JavaScript为句子加标题的3种方法示例

    前言 本文基于Free Code Camp基本算法脚本"标题案例一句". 在此算法中,我们要更改文本字符串,以便每个单词的开头始终都有一个大写字母. 在本文中,我将解释三种方法.首先使用FOR循环,其次使用map()方法,第三次使用replace()方法. 算法挑战 返回提供的字符串,每个单词的首字母大写.确保单词的其余部分为小写. 出于此练习的目的,你还应该大写连接词,例如" the"和" of". 提供的测试用例 titleCase(&quo

  • vue实现路由懒加载的3种方法示例

    前言 路由懒加载在访问页面的时候非常重要,能够提高首页加载速度,避免出现加载时候白页,如果没有懒加载,webpack打包后的文件会非常大. import按需加载(常用) vue异步组件 webpack提供的require.ensure() 1.import按需加载(常用) 允许将不同的组件打包到一个异步块中,需指定了相同的webpackChunkName. 把组件按组分块 const A = () => import(/* webpackChunkName: "group-A"

  • 利用JavaScript阻止表单提交的两种方法

    在JavaScript中,阻止表单默认提交行为的方法有两种,分别是: (1) return false 示例代码 <form name="loginForm" action="login.aspx" method="post"> <button type="submit" value="Submit" id="submit">Submit</button&g

  • 在JavaScript中判断整型的N种方法示例介绍

    整数类型(Integer)在JavaScript经常会导致一些奇怪的问题.在ECMAScript的规范中,他们只存在于概念中: 所有的数字都是浮点数,并且整数只是没有一组没有小数的数字. 在这篇博客中,我会解释如何去检查某个值是否为整型. ECMAScript 5 在ES5中有很多方法你可以使用.有时侯,你可能想用自己的方法:一个isInteger(x)的函数,如果是整型返回true,否则返回false. 让我们看看一些例子. 通过余数检查 你可以使用余数运算(%),将一个数字按1求余,看看余数

  • javascript 动态生成css代码的两种方法

    javascript 动态生成css代码的两种方法 有时候我们需要利用js来动态生成页面上style标签中的css代码,方法很直接,就是直接创建一个style元素,然后设置style元素里面的css代码,最后把它插入到head元素中.但有些兼容性问题我们需要解决.首先在符合w3c标准的浏览器中我们只需要把要插入的css代码作为一个文本节点插入到style元素中即可,而在IE中则需要利用style元素的styleSheet.cssText来解决.还需要注意的就是在有些版本IE中一个页面上style

  • jquery动态加载js三种方法实例

    复制代码 代码如下: <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="

  • 正则表达式实现字符串每4位后自动加空格效果(两种方法)

    需求:输入框中输入银行卡号(或其他)时,每4位自动加空格(如下图) 分析 方法一:监控输入框的keyup事件,当value值的长度为4,8,12,16时,插入空格字符串" "(vue中代码片段如下) <input type="text" v-model="bankCard" @keyup="bankCardKeyup"> bankCardKeyup (e) { let self = this // 如果是删除键,则

  • JavaScript中数组去重常用的五种方法详解

    目录 1.对象属性(indexof) 2.new Set(数组) 3.new Map() 4.filter() + indexof 5.reduce() + includes 补充 原数组 const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]; 1.对象属性(indexof) 利用对象属性key排除重复项 遍历数组,每次判断新数组中是否存在该属性,不存在就存储在新数组中 并把数组元素作为key,最后返

  • 使用JavaScript获取URL中的参数(两种方法)

    本文给大家分享两种方法使用js获取url中的参数,其中方法二是使用的正则表达式方法,大家可以根据需要选择比较好的方法,废话不多说了,直接看详细介绍吧. 方法一: //取url参数 var type = request("type") function request() { var query = location.search; var paras = arguments[0]; if (arguments.length == 2) { query = arguments[1]; }

  • JavaScript中数组去除重复的三种方法

    废话不多说了,具体方法如下所示: 方法一:返回新数组每个位子类型没变 function outRepeat(a){ var hash=[],arr=[]; for (var i = 0; i < a.length; i++) { hash[a[i]]!=null; if(!hash[a[i]]){ arr.push(a[i]); hash[a[i]]=true; } } console.log(arr); } outRepeat([2,4,4,5,"a","a"

随机推荐