1. 程式人生 > >JS-字串處理

JS-字串處理

更多字串用法: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