JS-字符串处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Crazy_SunShine/article/details/81237211

更多字符串用法:http://www.w3school.com.cn/jsref/jsref_obj_string.asp

1.字符串截取

const str = '123qwe'
console.log('slice<<<'+str.slice(1, 3))//1表示开始位置,3表示结束位置的下一位置
console.log('substring<<<'+str.substring(1, 3))//同上
console.log('substr<<<'+str.substr(1, 3))//1表示开始位置,3表示截取长度
slice<<<23
substring<<<23
substr<<<23q

详细使用参考:js字符串截取函数slice()、substring()、substr()

2.判断字符串是否包含另一字符串

const str = '123qwe'
console.log('包含<<<'+str.indexOf('3q'))//返回字符串首位所在的位置
console.log('不包含<<<'+str.indexOf('33'))//返回-1
包含<<<2
不包含<<<-1

3.根据某字符切割成数组

const str2 = 'How are you'
console.log('分割///'+str2.split(' '))
console.log('分割///'+str2.split('')) 
console.log('分割///'+str2.split(' ',2))
分割///How,are,you
分割///H,o,w, ,a,r,e, ,y,o,u
分割///How,are

4.截取字符串

const str2 = 'How are you'
console.log('分割///'+str2.slice(5))
console.log('分割///'+str2.slice(5,9)) 
console.log('分割///'+str2.slice(-1))
分割///re you
分割///re y
分割///u

猜你喜欢

转载自blog.csdn.net/Crazy_SunShine/article/details/81237211
今日推荐