[ES6系列-05]字符串相关操作更方便

【原创】 码路工人 Coder-Power

大家好,这里是码路工人有力量,我是码路工人,你们是力量。

github-pages
博客园cnblogs


今天的内容是,关于 ES6 JavaScript 中字符串操作的变化。


1. 模板字符串 Template String

之前要拼接一段字符串,包括插入变量的值,要用一堆引号和加号。
量小还凑合,大量拼接的话,人力手工就难以应付了,而且很容易出错。

比如,就是要手动(别问为什么,现找个例子不容易)去生成一个这样的片段,如图:

band

要用普通的拼接做出来,简直遭罪:

/* eg.0
 * concact string in old way
 *
 * content from:
 *   https://en.wikipedia.org/wiki/Scorpions_(band)
 *   没错,我就是喜欢听老歌
 */
//--------------------------------------
const band = {
    name: "Scorpions",
    country: "German",
    representativeWork: "Wind of Change",
    currentMembers:[
        {
            name: "Rudolf Schenker",
            discription: "rhythm & lead guitar, backing vocals (1965–present)"
        },
        {
            name: "Klaus Meine",
            discription: " lead vocals (1969–present)"
        },
        {
            name: "Matthias Jabs",
            discription: "lead & rhythm guitar, backing vocals (1978–present)"
        },
        {
            name: "Paweł Mąciwoda",
            discription: "bass, backing vocals (2003–present)"
        },
        {
            name: "Mikkey Dee",
            discription: "drums (2016–present)"
        }
    ],
    Awards:[
        {
            year: 1975,
            honours: ["Best German Live Band"]
        },
        {
            year: 2000,
            honours: [
                "Town of Hanover Plaque (German: Stadtplakette)",
                "2000: Entry into the Golden Book of Hanover",
                "Cultural Prize of the City of Hanover"
            ]
        }
    ]
}

function createBandInfo(band, showMembers, showAwards) {
    var elm = ''
    elm += '<div class="band-container" >'
    elm += '<h1>' + band.name + '</h1>'
    elm += '<hr><h2>Information</h2>'
    elm += '<ul><li>Band: ' + band.name + '</li><li>Country: ' + band.country + '</li><li>Repressentative Work: ' + band.repressentativeWork + '</li></ul>'
    elm += '</div>'

    // ...It's too long to write them all in the example...
    if(showMemebers){
        elm += '...todo...'
    }

    if(showAwards){
        elm += '...todo...'
    }

    return elm;
}

createBandInfo(band, true, true)

//--------------------------------------

看过之前文章的童鞋应该都见过模板字符串的用例了,前文中直接用的没有具体说明,这里来补上。

/* eg.1
 * concact string in ES6 using Template String
 */
//--------------------------------------
function createBandElm(band, showMembers, showAwards) {
    let elm = `
        <div class="band-container">
            <h1>${ band.name }</h1>
            <hr>
            <h2>Information</h2>
            <ul>
                <li>Band: ${ band.name }</li>
                <li>Country: ${ band.country }</li>
                <li>Repressentative Work: ${ band.repressentativeWork }</li>
            </ul>
            ...
            // ...It's too long to write them all in the example...
        </div>
    `
    return elm
}

createBandElm(band, true, true)
//--------------------------------------

因为太长的缘故,就不都写出来了,相信这简短的小片段已经足以说明问题。

  • 1.使用 反单引号(标准键盘里在Esc键下方,1键左边)来标记模板字符串
  • 2.使用${ } 来插入变量值
  • 3.可以自由换行,会原样输出

这,对比看一下,没有那么多成对的标签需要注意,没有大量成对的引号(有时候还需要单双引号都要用),不用写那么多加号,简直是 oasis 。。。

结构清晰不易错,书写简便选择我!--Template-String

用过Angular的知道,如果不单独作文件写模板,也是这么用的。

2. startsWith/endsWith/includes

这三个方法,分别用来判断

  • startsWith:  是否以某字符串开头
  • endsWith:  是否以某字符串结尾
  • includes:  是否包含某字符串

类似的功能,之前只能用indexOf('要查找的字符串')是否等于-1来判断,等于-1表示没有找到,否则返回找到的index值。

有人学习 JavaScript 会觉得,越来越像java,码工不搞java所以觉得,向C#靠近了。(换句话说 java 跟 C# 还是很像的)。语言嘛相互借鉴优秀的设计很正常。

C#string.Format方法着实方便,各种格式化,各种辅助函数。如果不够,还可以写扩展方法(method(this 类型 实例, 其它普通参数)感兴趣的可以了解一下)。
有点跑远了,话题收回来,javascript也给增加了工具函数,不用自己写通用函数,还是很方便的。

注意startsWithendsWith里面带着个s,这里不太习惯。

2.1 startsWith

正着数

/* eg.2
 * startsWith
 * searching from start
 */
//--------------------------------------
// 不指定起始查找位置
"Coder-Power".startsWith('Coder')

// 指定起始查找位置
"Coder-Power".startsWith('Coder', 0)    // true
"Coder-Power".startsWith('Coder', 1)    // false
//--------------------------------------
  • 不指定开始位置,默认从第0位开始查找
  • 指定开始位置,从左到右数;不匹配则返回false

2.2 endsWith

反着数?不,还是正着数

startsWith非常好理解,相对来说endsWith就稍微有点坑了。
但是相信我,码工能给你讲明白。

/* eg.3
 * endsWith
 * searching from start too
 */
//--------------------------------------
// 不指定起始查找位置
"Coder-Power".endsWith('Power')        // true

// 指定起始查找位置
"Coder-Power".endsWith('Power', 10)    // false

// 指定起始查找位置
"Coder-Power".endsWith('Power', 11)    // true
//--------------------------------------

第二个参数endPosition是指查找时,从第0位截至到第?位,末尾指定的这个index是不包含在内的。

于是,Coder-Power11位下标0~10,指定到10false,到11true

2.3 includes

与上面的相同,接收两个参数,第二个为可选参数

  • 第一个指定要查找的字符串
  • 第二个指定查找的其实位置,不指定时默认为0
/* eg.4
 * includes
 */
//--------------------------------------

// 不指定起始查找位置
"Coder-Power".includes("-")         // true

// 指定起始查找位置:包含
"Coder-Power".includes("-", 5)      // true

// 指定起始查找位置:不包含
"Coder-Power".includes("-", 6)      // false

//--------------------------------------

3.其它补充

repeat重复

repeat方法接收一个参数,表示重复次数。

感觉不怎么常用。

例:

"Coder-Power".repeat(2)
// Coder-PowerCoder-Power

以上就是本期总结的全部内容了。
希望对你有帮助,下期再见。


欢迎关注分享,一起学习提高吧。
QRCode/微信订阅号二维码
CoderPowerQRCode


posted on 2019-06-17 18:01  CoderMonkey  阅读(324)  评论(0编辑  收藏  举报

导航