把字符串的每个单词首个字母大写

1: 因为首个单词字母大写 ,要用到 String 对象的 提取 字符串指定的下标的字符串;一般我们都是习惯的三种方式:

  例子:str = 'hello word!'

(1): substr( start , [length])  start非负整数 , length可选:提取字符的长度 省略就是从 start到字符串尾

    str.substr(0 , 1) // 'h'

    str.substr(1) // 'ello word!'

    str.substr(-2) // 返回的就是一个空串(即长度为 0 的字符串)

 

(2):substring(start , [stop]) 提取字符串中介于两个指定下标之间的字符

    参数:可以是负数 ,与substr() 类似   substring(1 , 2)// 'e'

    注意:a:start = stop // 返回也是空  b:substring(start , [stop]) //提取在start开始 但不包括 stop 下标 

 

(3):slice( start , [end]) 与第二种类似 参数用法一样

 

讲完了:需要的 方法那就开始进入主题啦!!!!

 

这个我把它 封装在原型上,以后方便使用,看注释 比较详细。。。

Demo.prototype = {

perStUpper: function (str, separator) {
// 如:str = ’ we are the world ‘
// 把每个单词分开 不考虑有特殊字符
this.separator = separator || ' ';// 分隔符
var jopStr = str.replace(/(^\s*)|(\s*$)/g, '');// 去左右空格
//console.log(jopStr)
this.jopStr = jopStr.split(this.separator);// 分割字符串 返回 一个 数组
//console.log(this.jopStr)
for (var i = 0; i < this.jopStr.length; i++) {// 遍历数组每一项
this.jopStr[i] = this.jopStr[i].substring(0, 1).toUpperCase() + this.jopStr[i].substring(1);
// 首字母替换大写 拼接 重新放到原来的数组去
}
return this.jopStr.join(' ');// 把数组指定分隔符 进行分割 字符串 然后 返回
//this.jopStr.join(' ');
//console.log(this.jopStr.join(' '))

}

至于,怎么使用大家就不用多说了吧!! 多总结,多分享。。。

 

posted @ 2017-03-24 02:09  流舟  阅读(721)  评论(0编辑  收藏  举报