1.charAt( index )------根據(jù)索引值查找對應的字符串
const str = "hello world";
const result = str.charAt(1)
colsole.log( result ) //h
const otherstr = " ";
const otherresult = otherstr.charAt(1);
console.log( otherresult ) // 返回空字符串,并不返回null
console.log( typeof otherresult) //String
2.indexOf()------根據(jù)所提供的子字符串,返回子字符串所在位置
(1)
const str = "hello world";
const result = str.indexOf("e") //查找方式也要是一個字符串( 子字符串 )
console.log( result ) //1,返回的是對應字串的索引
(2)
//可以設(shè)定開始查找的索引的位置
const str = "hello world hello world"
const result = str.indexOf("h",6);//從第六個索引開始查找
console.log(result) //12
//ES6中可以根據(jù)includes查找子字符串是否在另一個子字符串中,
const str = " hello world";
const result = str.includes('hello');
console.log( result ) //true
(3).截取類方法:
substring(value1,value2)
value1: 起始位置
value2:結(jié)束位置
const str = "hello World!"
const newstr = str.substring(1,2)
console.log(newstr) // hell
//也可以接受一個參數(shù)
console.log(str.substring(1))//ello world
//不支持負數(shù),如果傳入負數(shù)則視為0
console.log(str.substring(-1))//hello world
//注:當傳入兩個參數(shù)時,若兩個參數(shù)中的其中一個為負數(shù),則不會返回任何值
slice()
該方法跟substring()方法很類似
區(qū)別是:slice()方法可以接受兩個參數(shù)都為負數(shù),
const str = "hello World"
console.log(str.slice(1));//ello world
console.log(str.slice(-1))//d
//兩個參數(shù)時并截取的到第二個參數(shù)所對應的字符串
console.log(str.slice(1,2))//e
console.log(str.slice(1,3));//el
(4).split()
作用:split() 方法用于把一個字符串分割成字符串數(shù)組
const str = " ABC";
console.log(str.split("")) //[ "A","B","C"]
console.log(str.split("",1)) //["A"] 只截取一個從第零個開始截取
//以某個字符為零界點進行分割
const str = "!A!B!C!D!"
const newstr = str.split("!") //
console.log(newstr) //["", "A", "B", "C", "D", ""] 以!號為基準進行"左右"分割
const newArr = newstr.filter(item => {
return item != ""
})
console.log(newArr); //["A", "B", "C", "D"]
例子:
const str = " ABC "
const a = str.split("")
const b = a.map(item => ({
d: "I" + item
}))
console.log(b)
//0: {d: "IA"}
// 1: {d: "IB"}
// 2: {d: "IC"}