1. 程式人生 > 其它 >js中的slice、substr、substring

js中的slice、substr、substring

技術標籤:筆記js索引字串

js中的slice、substr、substring

(均不改變原來字串的值)

var str = " 11xieYaoPeng is a employee gender man telephone 134xxxxxxxx  address jiangsuProvince suzhouShi tel kunShanShi threeWaterShawTree "
console.log(str.length) //126

一、查詢索引

1.從前往後找,結果為所要查詢字串首次出現的位置,
第二個引數為從該位置開始向後查詢字串,
未找到,查詢結果為-1

var syi = str.indexOf("man", 10)
console.log("man首次出現的位置", syi) //35

2.從後往前找,索引都是從前往後排序的

var lsy = str.lastIndexOf("man")
console.log("man最後出現的位置", lsy) //35

3.search與indexOf的功能相同,search無法設定從哪一個位置開始查詢,
indexOf無法設定更強大的搜尋值(正則表示式)

var position = str.search("tel"
) console.log("tel", position) //39

二、slice

1.擷取字串在14-16位置的字串,返回結果包括第一個位置,不包括第二個位置

var str1 = str.slice(14, 16)
console.log("擷取的字串1", str1) //is

2. 若引數只有一個,返回的結果為第二個位置之後所有的字串,原值不變

var str2 = str.slice(14)
console.log("擷取的字串2", str2)
// is a employee gender man telephone 134xxxxxxxx  address jiangsuProvince suzhouShi tel kunShanShi threeWaterShawTree 
console.log(str)

3.若沒有引數,返回結果為從0擷取到最後一個位置

var str3 = str.slice()
console.log("擷取的字串3", str3)
// 11xieYaoPeng is a employee gender man telephone 134xxxxxxxx  address jiangsuProvince suzhouShi tel kunShanShi threeWaterShawTree 

4. 從後往前擷取 (負值不適用於IE8及以前版本)

var str4 = str.slice(-19)
console.log("擷取的字串4", str4)
// threeWaterShawTree

5. 從後往前擷取,包括第一個位置的,不包括第二個位置的

var str5 = str.slice(-19,-14)
console.log("擷取的字串5", str5)
// three

三、substr

1.第一個引數代表所要擷取的位置,第二個引數代表擷取的字串的長度

var str6 = str.substr(100,10)
console.log("擷取的字串6:",str6)
// kunShanShi

2.擷取位置及之後的字串

var str7 = str.substr(100)
console.log("擷取的字串7:",str7)
// kunShanShi threeWaterShawTree 

3.第一個引數為負數,從後往前查詢倒數第一百的位置,擷取長度為十的字串

var str8 = str.substr(-100,10)
console.log("擷取的字串8:",str8)
// nder man t

4.因為第二個引數代表擷取字串的長度,所以不能為負值,
若第二個引數為負值,返回結果為空字串

var str9 = str.substr(100,-10)
console.log("擷取的字串9:",str9 == "") 
// true

5.若只有一個引數,且為負值,從後往前檢索至倒數第十九的位置,並返回剩餘的字串

var str10 = str.substr(-19)
console.log("擷取的字串10:",str10)
// threeWaterShawTree 

四、substring

var string1 = "hahaha xixixi zezeze"

1.擷取第二到第七的字串

var str11 = string1.substring(7,2)
console.log("擷取的字串:",str11)
// haha 

2.若第一個引數為負值,則表示從字串的第一個位置開始擷取,擷取到第二個引數所在的位置

var str12 = string1.substring(-7,8)
console.log("擷取的字串:",str12)
// hahaha x

3.若只有一個引數,且引數為負值,與沒有引數時情況相同,擷取整個字串

var str13 = string1.substring(-7)
console.log("擷取的字串:",str13)
// hahaha xixixi zezeze
var str14 = string1.substring()
console.log("擷取的字串:",str14)
// hahaha xixixi zezeze

5.若兩個引數都為負值,即代表從開始位置擷取到開始位置,結果為空字串

var str15 = string1.substring(-1,-2)
console.log("擷取的字串:",str15 === "")
// true
console.log(string1)
// hahaha xixixi zezeze
console.log(str)
// 11xieYaoPeng is a employee gender man telephone 134xxxxxxxx  address jiangsuProvince suzhouShi tel kunShanShi threeWaterShawTree