1.字符串方法_charAt()
charAt 方法返回指定位置的字符,参数是从 0 开始编号的
例子:
var s = new String('itbaizhan');
s.charAt(1) // "t"
s.charAt(s.length - 1) // "n"
如果参数为负数,或大于等于字符串的长度, charAt 返回空字符串
'itbaizhan'.charAt(-1) // " "
'itbaizhan'.charAt(9) // " "
2.字符串方法_concat()
concat 方法用于连接两个字符串,返回一个新字符串,不改变原字符串
例子:var s1 = 'itbaizhan';
var s2 = 'sxt';
s1.concat(s2) // "itbaizhansxt"
s1 // "itbaizhan"
该方法可以接受多个参数
'sxt'.concat('itbaizhan', 'bjsxt') // "sxtitbaizhanbjsxt"
如果参数不是字符串, concat 方法会将其先转为字符串,然后再连接
var one = 1;
var two = 2;
var three = '3';
' '.concat(one, two, three) // "123"
例:
var one = 1;
var two = 2;
var three = '3';
console.log(''.concat(one, two, three) ) // 123
console.log(one + two + three ) //33
3.字符串方法_substring()
substring 方法用于从原字符串取出子字符串并返回,不改变原字符串。
它的第一个参数表示子字符串的开始位置,
第二个位置表示结束位置(返回结果不含该位置)
'itbaizhan'.substring(0, 2) // "it"
如果省略第二个参数,则表示子字符串一直到原字符串的结束
'itbaizhan'.substring(2) // "baizhan"
如果第一个参数大于第二个参数, substring 方法会自动更换两个参数 的位置
'itbaizhan'.substring(9, 2)
// "baizhan" // 等同于 'itbaizhan'.substring(2, 9) // "baizhan"
如果参数是负数, substring 方法会自动将负数转为0
'itbaizhan'.substring(-3) // "itbaizhan"
'itbaizhan'.substring(2, -3) // "it"
4.字符串方法_substr()
substr 方法用于从原字符串取出子字符串并返回,不改变原字符串, 跟 substring 方法的作用相同
substr 方法的第一个参数是子字符串的开始位置(从0开始计算), 第二个参数是子字符串的长度
'itbaizhan'.substr(2, 7); // baizhan
如果省略第二个参数,则表示子字符串一直到原字符串的结束
'itbaizhan'.substr(2) // "baizhan"
如果第一个参数是负数,表示倒数计算的字符位置。如果第二个参 数是负数,将被自动转为0,
因此会返回空字符串
'itbaizhan'.substr(-7) // "baizhan"
'itbaizhan'.substr(4, -1) // " "
5.字符串方法_indexOf()
indexOf 方法用于确定一个字符串在另一个字符串中第一次出现的位 置,返回结果是匹配开始的位置。
如果返回 -1 ,就表示不匹配
'hello world'.indexOf('o') // 4
'itbaizhan'.indexOf('sxt') // -1
indexOf 方法还可以接受第二个参数,表示从该位置开始向后匹配
'hello world'.indexOf('o', 6) // 7
'itbaizhan'.indexOf("z",6) //-1
6.字符串方法_trim()
trim 方法用于去除字符串两端的' hello world '.trim() // "hello world"空格,
返回一个新字符串,不改变原 字符串
' hello world '.trim() // "hello world"
该方法去除的不仅是空格,还包括制表符( \t 、 \v )、换行符 ( \n )和回车符( \r )
'\r\nitbaizhan \t'.trim() // 'itbaizhan'
ES6扩展方法, trimEnd() 和 trimStart() 方法
" itbaizhan ".trimEnd(); // itbaizhan
" itbaizhan ".trimStart(); // itbaizhan
7.字符串方法_split()
split 方法按照给定规则分割字符串,返回一个由分割出来的子字符 串组成的数组
'it|sxt|baizhan'.split('|') // ["it", "sxt", "baizhan"]
如果分割规则为空字符串,则返回数组的成员是原字符串的每一个 字符。
'a|b|c'.split('') // ["a", "|", "b","|", "c"]
"itbaizhan".split(""); // ['i', 't', 'b', 'a', 'i', 'z', 'h', 'a', 'n']
如果省略参数,则返回数组的唯一成员就是原字符串
'it|sxt|bz'.split() // [it|sxt|bz]
split 方法还可以接受第二个参数,限定返回数组的最大成员数。
'it|sxt|bz'.split('|', 0) // [ ]
'it|sxt|bz'.split('|', 1) // ["it"]
'it|sxt|bz'.split('|', 2) // ["it", "sxt"]
'it|sxt|bz'.split('|', 3) // ["it", "sxt", "bz"]
'it|sxt|bz'.split('|', 4) // ["it", "sxt", "bz"]
字符串的方法小例题
于 2022-11-30 15:50:34 首次发布