JS字符串常用方法(自)---4、子串


JS字符串常用方法(自)---4、子串

一、總結

一句話總結:

js獲取子串的方法有string.slice(start, end)提取一個字符串,string.substring(start, end)提取一個字符串,end不支持負數
slice()
作用:對字符串進行切片
參數:必帶beginIndex,可選endIndex
返回值:返回一個從原字符串中提取出來的新字符串

substring()
作用:截取子串
參數:必帶的indexStart(截取開始索引),indexEnd(截取結束索引)
返回值:截取的子串

 

 

1、substring()方法截取子串的時候,關於參數indexStart和indexEnd的注意點是時候?

substring()方法留頭不留尾,也就是截取的子串包含indexStart,不包含indexEnd

 

2、js中截取子串函數slice和SubString的區別?

string.slice(start, end)提取一個字符串
string.substring(start, end)提取一個字符串,end不支持負數

 

3、string.slice(start, end)提取一個字符串中,start和end為負數是什么情況?

如果 start或end 是 -3,則表示strLength - 3,例如:console.log('The quick brown fox'.slice(-5,-1));//n fo

 

 

二、獲取子串

博客對應課程的視頻位置:

 

1、string.slice(start, end)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>slice()</title>
 6 </head>
 7 <body>
 8 <!--
 9 slice()
10 作用:對字符串進行切片
11 參數:必帶beginIndex,可選endIndex
12 返回值:返回一個從原字符串中提取出來的新字符串
13 
14 string.slice(start, end)提取一個字符串中,start和end為負數是什么情況
15 如果 start或end 是 -3,則表示strLength - 3,例如:console.log('The quick brown fox'.slice(-5,-1));//n fo
16 
17 -->
18 <script>
19     console.log('The quick brown fox'.slice(1,5));//he q
20     console.log('The quick brown fox'.slice(-5,-1));//n fo
21 
22     //自己寫簡略的slice函數
23     String.prototype.slice_my=function(beginIndex,endIndex){
24         let ans_str='';
25         endIndex=this.length>endIndex?endIndex:this.length;
26         for(let i=beginIndex;i<endIndex;i++){
27             ans_str+=this[i];
28         }
29         return ans_str;
30         //console.log(this);
31     };
32     //'The quick brown fox'.slice_my(1,5);
33     console.log('The quick brown fox'.slice_my(1,5));
34 </script>
35 </body>
36 </html>

 

 

2、string.substring(start, end)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>substring()</title>
 6 </head>
 7 <body>
 8 <!--
 9 substring()
10 作用:截取子串
11 參數:必帶的indexStart(截取開始索引),indexEnd(截取結束索引)
12 返回值:截取的子串
13 
14 substring()方法截取子串的時候,關於參數indexStart和indexEnd的注意點是時候
15 substring()方法留頭不留尾,也就是截取的子串包含indexStart,不包含indexEnd
16 
17 js中截取子串函數slice和SubString的區別
18 string.slice(start, end)提取一個字符串
19 string.substring(start, end)提取一個字符串,end不支持負數
20 
21 -->
22 <script>
23     var anyString = "Mozilla";
24     console.log(anyString.substring(1));
25     console.log(anyString.substring(1,3));//'oz'
26 
27 </script>
28 </body>
29 </html>

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM