JavaScript 字符串方法

length 属性

返回字符串的长度

1
2
let str = "shaoin";
console.log(str.length) // 6

split() 方法

将字符串转换为数组

1
2
3
let str = "shaoin";
console.log(str.split('ao')) // ["sh", "in"]
console.log(str.split('')) // ["s", "h", "a", "o", "i", "n"]

search() 方法

该方法设置一个参数:需要搜索的字符串。

搜索特定的字符串,并返回位置

1
2
3
let str = "shaoin";
console.log(str.search('ao')) // 2
console.log(str.search('bo')) // -1

slice() 方法

该方法设置两个参数:起始索引(开始位置),终止索引(结束位置)。[ 左闭右开 )

提取参数对应位置的字符,并返回新的字符串。

1
2
3
let str = "shaoin";
console.log(str.slice(3,5)) // "oi"
console.log(str.slice(2)) // "aoin"

substr() 方法

该方法设置两个参数:起始索引(开始位置),提取字符的长度。

提取参数对应位置及长度的字符,并返回新的字符串。

1
2
3
let str = "shaoin";
console.log(str.substr(3,2)) // "oi"
console.log(str.substr(2)) // "aoin"

replace() 方法

该方法设置两个参数:需要被替换的字符串,替换成新的字符串。

不改变原来的字符串,返回新的字符串。

1
2
let str = "shaoin in"
console.log(str.replace('in','oo')) // "shaooo in" 注意:按顺序匹配首个遇到的字符

可以通过正则表达式,扩展替换的功能。

concat() 方法

连接连个或者多个字符串;

1
2
3
4
5
let str = "";
let str1 = "my ";
let str2 = "name's ";
let str3 = "shaoin";
console.log(str.concat(str1,str2,str3)) // "my name's shaoin"

trim() 方法

删除字符串两端的空白符。

1
2
let str = " shaoin ";
console.log(str.trim()); // 'shaoin'

JavaScript 数值方法

toString() 方法

将数字转换成字符串。

1
2
let num = 11;
console.log(num.toString) // "11"

toFixed() 方法

返回一个指定位数小数的字符串。

1
2
3
4
let num = 11.1;
num.toFixed(0) // '11'
num.toFixed(1) // '11.1'
num.toFixed(2) // '11.10'

Number() 方法

将变量转换为数值。

1
2
3
let str = '11',bool = true;
console.log(Number(str)) // 11
console.log(Number(bool)) // 1

JavaScript 数组方法

join() 方法

该方法设置一个参数:数组中元素以什么方式连接。

将数组元素结合为一个字符串。

1
2
3
let arr = ["s", "h", "a", "o", "i", "n"];
console.log(arr.join('')) // "shaoin"
console.log(arr.join('*')) // "s*h*a*o*i*n"

pop() 方法

从原数组中删除最后一个元素。

1
2
3
let arr = ["s", "h", "a", "o", "i", "n"];
arr.pop(); // "n"
console.log(arr) // ["s", "h", "a", "o", "i"]

push() 方法

在原数组结尾处添加一个新的元素。

1
2
3
let arr = ["s", "h", "a", "o", "i", "n"];
arr.push('a') // 7
console.log(arr) // ["s", "h", "a", "o", "i", "n", "a"]

shift() 方法

删除原数组的首个元素。

1
2
3
let arr = ["s", "h", "a", "o", "i", "n"];
arr.shift() // "s"
console.log(arr) // ["h", "a", "o", "i", "n"]

unshift() 方法

在原数组首位添加一个新的元素。

1
2
3
let arr = ["s", "h", "a", "o", "i", "n"];
arr.unshift("a") // 7
console.log(arr) // ["a", "s", "h", "a", "o", "i", "n"];

splice() 方法

该方法有多个参数:第一个参数定义添加新元素和删除旧元素的位置;第二个参数定义删除元素的位数;其余参数皆为要添加到数组中的元素。

返回一个包含一删除项的数组

1
2
3
let arr = ["s", "h", "a", "o", "i", "n"];
arr.splice(3,1,"i","i") // ["0"]
console.log(arr) // ["s", "h", "a", "i", "i", "i", "n"]