ES5与ES6字符串方法总结

ES5

检索字符串

indexOf

与数组方法相似。正则表达式

stringObject.indexOf(searchvalue,fromindex)

fromindex规定在字符串中开始检索的位置。它的合法取值是 0 到 stringObject.length - 1。如省略该参数,则将从字符串的首字符开始检索。数组

lastIndexOf

与indexOf相反。函数

indexOf和lastIndexOf方法对大小写敏感!

截取字符串

slice(start, end)

  1. start,要抽取的片段的起始下标,若是为负,则从尾部算起。
  2. end,要抽取的片断的结尾的下标,若是为负,则从尾部算起。
String.slice() 与 Array.slice() 类似

substring(start, stop)

  1. start必需。要抽取的片段的起始下标,不能为负。
  2. stop可选。比要提取的子串的最后一个字符的位置多1,不能为负。
若是参数 start 与 stop 相等,那返回一个空串。
若是 start 比 stop 大,那在提取子串以前会先交换这两个参数。
若是同时为负,则返回空串。
若是一个值为负,则转为0,并且若是start 比 stop 大,会交换值。

substr(start, length) --不推荐

  1. start,要抽取的片段的起始下标,若是为负,则从尾部算起。
  2. length,若是为负,则转为0。

trim(),trimLeft(),trimRight()

去除首尾空格。字体

正则相关

split

把一个字符串分割成字符串数组。编码

stringObject.split(separator, howmany)     //separator必需,字符串或正则表达式
var str="How are you doing today?";
str.split(/\s+/);      //"How", "are", "you", "doing", "today?"
若是把空字符串 ("") 用做 separator,那么 stringObject 中的每一个字符之间都会被分割。
String.split() 执行的操做与 Array.join 执行的操做是相反的。

match

可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。code

stringObject.match(searchvalue | reg)

字符串检索regexp

var str="Hello world!";
str.match('w');      //["w", index: 6, input: "Hello world!", groups: undefined]

正则检索对象

// 全局匹配
var str="1 plus 2 equal 3";
str.match(/\d+/g);      //["1", "2", "3"]

var str="1 plus 2 equal 3";
str.match(/\d+/);      //["1", index: 0, input: "1 plus 2 equal 3", groups: undefined]

replace

用于在字符串中用一些字符替换另外一些字符,或替换一个与正则表达式匹配的子串。ip

stringObject.replace(reg | substr, replacement)

字符串替换字符串

'aaaccc'.replace('ccc', 'b');    //'aaab'

'aaaccc'.replace('bbb', 'b');    //'aaaccc'

'aaaccc'.replace('a', 'b');     //"baaccc"

正则替换

'aaaccc'.replace(/\w/, 'b')     //"baaccc"

//全局匹配
'aaaccc'.replace(/\w/g, 'b')    //"bbbbbb"

replacement
replacement 能够是字符串,也能够是函数。可是 replacement 中的 $ 字符具备特定的含义。

字符 替换文本
字符 替换文本
$一、$二、...、$99 与 regexp 中的第 1 到第 99 个子表达式相匹配的文本。
$& 与 regexp 相匹配的子串。
$` 位于匹配子串左侧的文本。
$' 位于匹配子串右侧的文本。
$$ 直接量符号。
'aa123BB'.replace(/([a-z]+)(\d+)([A-Z]+)/g, '$1'); // "aa"
'aa123BB'.replace(/([a-z]+)(\d+)([A-Z]+)/g, '$4'); // "$4"
    
'aa123BB'.replace(/([a-z]+)(\d+)([A-Z]+)/g, '$&'); //"aa123BB"
'aa123BB'.replace(/(\d+)/g, '$`'); //"aaaaBB"
'aa123BB'.replace(/(\d+)/g, "$'"); //"aaBBBB"
'aa123BB'.replace(/(\d+)/g, '$$'); //"aa$BB"
ECMAScript v3 规定,replace() 方法的参数 replacement 能够是函数而不是字符串。在这种状况下,每一个匹配都调用该函数,它返回的字符串将做为替换文本使用。
'aaaccc'.replace(/\w/g, function() {
    return 'b';
});
//"bbbbbb"

'aaaccc'.replace(/\w/, function() {
    return 'b';
});
//"baaccc"

search

stringObject.search(searchvalue | reg)
'aaaccc'.search('ccc');    //3
'aaaccc'.search(/ccc/);    //3  
var str="Visit W3School!";
str.search(/W3School/);    //6
search() 对大小写敏感

其余

  1. big() 用大号字体显示字符串。
  2. blink() 显示闪动字符串。
  3. bold() 使用粗体显示字符串。
  4. sup() 把字符串显示为上标。
  5. sub() 把字符串显示为下标。
  6. strike() 使用删除线来显示字符串。
  7. small() 使用小字号来显示字符串。
  8. charAt() 返回在指定位置的字符。
  9. charCodeAt() 返回在指定的位置的字符的 Unicode 编码。
  10. toLocaleLowerCase() 把字符串转换为小写。
  11. toLocaleUpperCase() 把字符串转换为大写。
  12. toLowerCase() 把字符串转换为小写。
  13. toUpperCase() 把字符串转换为大写。
  14. toSource() 表明对象的源代码。
  15. toString() 返回字符串。
  16. valueOf() 返回某个字符串对象的原始值。

ES6

includes(), startsWith(), endsWith()

  • includes(searchValue, start):返回布尔值,表示是否找到了参数字符串。
  • startsWith(searchValue, start):返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith(searchValue, start):返回布尔值,表示参数字符串是否在原字符串的尾部。
let s = 'Hello world!';

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

repeat(value)

返回一个新字符串,表示将原字符串重复n次。

  • 若是value数是负数或者Infinity,会报错。可是,若是参数是 0 到-1 之间的小数,则等同于 0。
  • 若是value是字符串,则会先转换成数字。
  • value为NaN等同于 0。
  • value若是是小数,会被取整。
'a'.repeat(3);     // "aaa"
'a'.repeat(-1);    //VM449:1 Uncaught RangeError: Invalid count value
'a'.repeat('3n');  //""
'a'.repeat('3');   //"aaa"
'a'.repeat(NaN);   //""
'a'.repeat(1.6);   //"a"

padStart(),padEnd()

  • padStart(length, string)用于头部补全。
  • padEnd(length, string)用于尾部补全。
'aaa'.padStart(2, 'ab');            //"aaa"
'aaa'.padStart(10, '0123456789');   //"0123456aaa"
'aaa'.padStart(10)                  //"       aaa"
'aaa'.padEnd(6, 'cd')               //"aaacdc"

模板字符串

模板字符串(template string)是加强版的字符串,用反引号(`)标识。

let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`    //"Hello Bob, how are you today?"

模板字符串中嵌入变量,须要将变量名写在${}之中。

JS表达式,能够进行运算,以及引用对象属性

let x = 1;
let y = 2;
`${x} + ${y} = ${x + y}`        //"1 + 2 = 3"

var obj = { a: 'eee'}
`obj ${obj}`                   //"obj [object Object]"

调用函数

function fn() {
  return "Hello World";
}

`foo ${fn()} bar`             //"foo Hello World bar"

标签模板

模板字符串能够紧跟在一个函数名后面,该函数将被调用来处理这个模板字符串。这被称为“标签模板”功能(tagged template)。

alert`123`;  等同于alert(123);

若是模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数。

let a = 5;
let b = 10;

function tag(s, v1, v2) {
  console.log(s);
  console.log(v1);
  console.log(v2);

  return "OK";
}

tag`Hello ${ a + b } world ${ a * b}`;
// 等同于 tag(['Hello ', ' world ', ''], 15, 50);

//["Hello ", " world ", "", raw: Array(3)]
//15
//50
//"OK"
相关文章
相关标签/搜索