字符串属性加方法

字符串

属性

var str='hello world'
console.log(str.length);
==> 11 长度属性
​
console.log(str[0]);
==>h 字符串有下标
​
console.log(str[str.length-1]);
==>d
//字符串下标不能随意更改

方法

slice

从已有的数组中返回选定的元素。

var str='hello world'
console.log(str.slice());
==>hello world 返回所有字符串
​
console.log(str.slice(2));
==>llo world 返回从下标为2开始的剩余字符串
​
console.log(str.slice(2,4));
==>ll start 开始下标 end结束下标(不包含) 参数可以为负数
​
console.log(str.slice(-2));
==>ld 空格也算哦

substr

抽取从 start 下标开始指定数目字符。

var str='hello world'
console.log(str.substr(2,3));
==>llo 
//与slice的区别是第二个参数是长度的意思

substring

提取介于两个指定下标间字符。

var str='hello world'
console.log(str.substring(2,4));
==> ll 参数不能为负

indexOf()

返回数组中某个指定的元素位置

var str='hello world'
console.log(str.indexOf('l'));
==>2 查找指定字符首次出现的位置
​
console.log(str.indexOf('l',4));
==>9 第二个参数是搜索的起码位置
​
console.log(str.lastIndexOf('l'));
==> 9 从后向前搜索 指定字符首次出现的位置
​
​

search

查找指定字符首次出现的位置

var str='hello world'
console.log(str. search('l'));// 2 
==>查找指定字符首次出现的位置,可以传入正则表达式,只有一个参数

 

replace

替换字符

var str='hello world'
var subStr=str.replace(查找的子串,新的值)
var subStr=str.replace('e','a')
console.log(subStr) ;
==>hallo world

concat

拼接字符

var str='hello world'
var newStr=str.concat('你好')//拼接
console.log(newStr);
==>hello world你好

split()

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

var str='hello,world,你好'
console.log(str.split());
==>返回一个数组
​
console.log(str.split(''));
//把每个字符拆分 组成一个数组
==>["h", "e", "l", "l", "o", ",", "w", "o", "r", "l", "d", ",", "你", "好"]
​
console.log(str.split(','));//以指定字符拆分
==>["hello,world,你好"]
​
console.log(str.split('o'));
==>["hell", ",w", "rld,你好"]
​
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值