ECMAScript 6(6)字符串新增方法 (includes(),startsWith()...)

    xiaoxiao2022-07-03  154

    字符串的新增方法

    includes(), startsWith(), endsWith()

    语法:

    str.includes(searchString[, position]) str.startsWith(searchString[, position]) str.endsWith(searchString[, position])

     说明 : 

    includes():返回布尔值,表示是否找到了参数字符串。startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。参数 :  第一个参数是要查找的字符串, 第二个参数是从哪个位置开始 let s = 'Hello world!'; s.startsWith('Hello') // true s.endsWith('!') // true s.includes('o') // true

    这三个方法都支持第二个参数,表示开始搜索的位置。

    let s = 'Hello world!'; s.startsWith('world', 6) // true s.endsWith('Hello', 5) // true s.includes('Hello', 6) // false

    repeat() 

    语法 :

    str.repeat(count)

    说明 :

    1. 简单来说,就是将str这个字符串重复count次并返回; 2. 参数类型要求是number类型(或被隐式转换为number类型); 3. 参数的值要求是非负整数次(包括0),浮点数会被取整(舍去小数部分); 4. 非法参数会抛出异常;

    示例代码 :

    var str = "abc"; str.repeat(0); //"" str.repeat(1); //"abc" str.repeat(2); //"abcabc" str.repeat(1.9); //"abc" str.repeat(-1); //Uncaught RangeError: Invalid count value

     padStart(),padEnd()  (ES2017)

    语法 :

    str.padStart(length [, padString]) str.padEnd(length [, padString])

     说明 :

    1. 字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。

    2.padStart()用于头部补全,

    3.padEnd()用于尾部补全。

    示例代码 : 

    'x'.padStart(5, 'ab') // 'ababx' 'x'.padStart(4, 'ab') // 'abax' 'x'.padEnd(5, 'ab') // 'xabab' 'x'.padEnd(4, 'ab') // 'xaba' '12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12" '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
    最新回复(0)