JavaScript中的字符串相关操作

CharAt()

charAt()方法返回给定的索引位置的字符,索引从0开始;

let str="abcdefg";
conlose.log(charAt(3)); // d

concat()

将一个或多个字符串拼接成一个新的字符串。

let str="hello";
let re=str.concat(" world!");

console.log(re);// hello world!

concat()可以接收一个或多个参数;

let str="hello";
let re=str.concat(" world","!");

console.log(re);// hello world!

slice()、substr()、substring()\

slice()、substr()、substring()三个方法都返回调用他们的字符串的一个子串;
它们接受一个或两个参数。第一个表示子字符串开始的位置,第二个表示子字符串结束的位置。对于slice()和substring()第二个参数是提取结束的位置(即给位置支付前的字符会被提取出来);对于substr(),第二个参数是子串的长度。三个方法省略第二个参数意味着提取到字符串末尾。
如果参数是负数,
slice():所有负数 当做字符串长度加上负数的结果
substr():第一个参数负值当成字符串长度加上负值,第二个参数当做0
substring():会将所有负参数当做0

let str="hello world";
console.log(str.slice(3));// lo world
console.log(str.substr(3));// lo world
console.log(str.substring(3));// lo world

console.log(str.slice(3,7));// lo w
console.log(str.substr(3,7));// lo worl
console.log(str.substring(3,7));// lo w

console.log(str.slice(-3));// rld
console.log(str.substr(-3));// rld
console.log(str.substring(-3));// hello world

console.log(str.slice(3,-4));// lo w
console.log(str.substr(3,-4));//
console.log(str.substring(3,-4));// hel 

indexOf()、lastindexOf()

两个方法都返回传入字符在字符串中的位置。
区别在于
indexOf():从字符串开头开始查找,从前往后;
lastindexOf():从字符串末尾开始查找,从后往前;
这两个方法接收第二个参数,表示开始查找的位置;

let str="hello world";
console.log(str.indexOf("o"));// 4
console.log(str.lastIndexOf("o"));// 7 

console.log(str.indexOf("o",5));// 7
console.log(str.lastIndexOf("o",6));// 4 

trim()

trim()方法会创建一个字符串的副本,删除前后所有的空格,返回结果。
trim()返回的是字符串的副本,原字符串不会受到影响。
另外 trimLeft()和trimRight()分别用于清楚字符串开头和末尾的空格。

repeat()

repeat()方法接收一个整数参数,表示需要将字符串复制多少次,然后返回拼接所有副本后的结果。
padStart(): 复制字符串,若小于指定长度,在左边填充字符。 第二个参数表示用于填充的字符;
padEnd(): 复制字符串,若小于指定长度,在右边填充字符。 第二个参数表示用于填充的字符;

字符串的大小写转换

toUpperCase(): 将字符串转换为大写;
toLowerCase(): 将字符串转换为小写。

split()

split()方法接收两个参数,第一个是一个字符串或者正则表达式,第二个是指定返回数组的最大长度(可选);方法返回字符串分割成的字符串数组。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值