JavaScript里處理字符串的一些常用方法


1.length 屬性返回字符串的長度

let srt = "hello world!";
console.log(srt.length) // 12

2.indexOf() 方法可返回某個指定的字符串值在字符串中首次出現的位置。

let str="Hello world!"
console.log(str.indexOf("Hello")); // 0
console.log(str.indexOf("World")); // -1
console.log(str.indexOf("world")); // 6
  • indexOf() 方法對大小寫敏感!

如果要檢索的字符串值沒有出現,則該方法返回 -1。常用來判斷是否含有該字符

let url = 'https://www.cnblogs.com/imMeya/p/11492490.html'
      if(url.indexOf("?") == -1){
        console.log("url中沒有'?'");
      }else{
        console.log("含有");
      }
      // -> url中沒有'?'

3.lastIndexOf() 方法返回指定文本在字符串中最后一次出現的索引

  • 如果未找到文本, indexOf() 和 lastIndexOf() 均返回 -1
  •  indexOf() 和 lastIndexOf()兩種方法都接受作為檢索起始位置的第二個參數。
let srt = "hello world! hello china";
console.log(srt.lastIndexOf('hello')) // 13
console.log(srt.indexOf('hello',5)) //13

4.search() 方法搜索特定值的字符串,並返回匹配的位置

  • indexOf() 與 search(),是相等的。

這兩種方法的區別在於:

  1. search() 方法無法設置第二個開始位置參數。
  2. indexOf() 方法無法設置更強大的搜索值(正則表達式)。
let str="Hello world!"
console.log(str.search("Hello")); // 0
console.log(str.search("World")); // -1
console.log(str.search("world")); // 6

 

5.substring() 方法用於提取字符串中介於兩個指定下標之間的字符。

  • substring() 不接受負的參數。
let str="Hello world!"
console.log(str.substring(3,7)); // lo wo
console.log(str.substring(3)); // lo world!

6.slice() 方法可提取字符串的某個部分,並以新的字符串返回被提取的部分。

let str="Hello world!"
console.log(str.slice(3,7)); // lo w
console.log(str.slice(3)); // lo world!
console.log(str.slice(-2)); // d! 。如果是負數,則該參數規定的是從字符串的尾部開始算起的位置。也就是說,-1 指字符串的最后一個字符,-2 指倒數第二個字符,以此類推。

7.substr() 方法可在字符串中抽取從 start 下標開始的指定數目的字符。

stringObject.substr(start,length)
let str="Hello world!"
console.log(str.substr(3)); // lo world!
console.log(str.substr(3,2)); // lo

 

String 對象的方法 slice()、substring()都可返回字符串的指定部分。slice() 比 substring() 要靈活一些,因為它允許使用負數作為參數。

8.replace() 方法用另一個值替換在字符串中指定的值。

  • replace() 方法不會改變調用它的字符串。它返回的是新字符串。
  • replace() 方法對大小寫敏感!
let str = "Hello world!";
console.log(str.replace('Hello','Hi'));  // Hi world!   
  •  如需執行大小寫不敏感的替換,請使用正則表達式 /i(忽略大小寫)
  • 請注意正則表達式不帶引號。
let str = "Hello world!";
console.log(str.replace(/hello/i,'Hi'));  // Hi world!   

默認地,replace() 只替換首個匹配

如需替換所有匹配,請使用正則表達式的 g 標志(用於全局搜索)

let str = "Hello world! hello China !";
console.log(str.replace(/hello/ig,'Hi'));  // Hi world! Hi China ! 

9.toUpperCase() 把字符串轉換為大寫

let text = 'Hello world!';
console.log(text.toUpperCase()) //HELLO WORLD!

10.toLowerCase() 把字符串轉換為小寫

let text = 'HELLO WORLD!';
console.log(text.toLowerCase()) // hello world!

11.concat() 連接兩個或多個字符串

  • concat() 方法可用於代替加運算符。
  • 所有字符串方法都會返回新字符串。它們不會修改原始字符串
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
console.log(text3); //Hello world!
  • concat() 方法可用於代替加運算符。下面兩行是等效的
let text = "Hello" + " " + "World!";
let text = "Hello".concat(" ","World!"); //Hello world!

12.trim() 方法刪除字符串兩端的空白符

let str = "       Hello World!        ";
console.log(str.trim()); //Hello world!
  • Internet Explorer 8 或更低版本不支持 trim() 方法。
  • 如需支持 IE 8,您可搭配正則表達式使用 replace() 方法代替
let str = "       Hello World!        ";
console.log(str.trim()); //Hello world!
console.log(str.replace(/\s+/g,'')); // HelloWorld!  去掉所有空格
console.log(str.replace(/(^\s*)|(\s*$)/g,'')); //Hello world! 去掉前后空格

13.charAt() 方法返回字符串中指定下標(位置)的字符串

let str = 'Hello World!';
console.log(str.charAt(0)) //H
console.log(str[0]); //H 此方法不建議使用

14.charCodeAt() 方法返回字符串中指定索引的字符 unicode 編碼

let str = 'Hello World!';
console.log(str.charCodeAt(0)) // 72

15.split() 將字符串轉換為數組

let txt = "h,e,l,l,o";   
console.log(txt.split(","));  // ["h", "e", "l", "l", "o"]  用逗號分隔
console.log(txt.split(" "));  // ["h,e,l,l,o"]  用空格分隔
//如果分隔符是 "",被返回的數組將是間隔單個字符的數組
let txt2 = "Hello";       
console.log(txt2.split(""));   // ["h", "e", "l", "l", "o"]  分隔為字符

16.match()使用正則表達式與字符串相比較。

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);

console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

使用match不傳參數

var str = "Nothing will come of nothing.";

str.match();   //  [""]

 

17.padEnd()在當前字符串尾部填充指定的字符串, 直到達到指定的長度。 返回一個新的字符串。

  • srt.padEnd(targetLength [,padString])
  • 當前字符串需要填充到的目標長度。如果這個數值小於當前字符串的長度,則返回當前字符串本身。
'abc'.padEnd(10);          // "abc       "
'abc'.padEnd(10, "foo");   // "abcfoofoof"
'abc'.padEnd(6, "123456"); // "abc123"
'abc'.padEnd(1);           // "abc"

 

18.padStart()在當前字符串頭部填充指定的字符串, 直到達到指定的長度。 返回一個新的字符串。

  • srt.padEnd(targetLength [,padString])
  • 當前字符串需要填充到的目標長度。如果這個數值小於當前字符串的長度,則返回當前字符串本身。
'abc'.padStart(10);         // "       abc"
'abc'.padStart(10, "foo");  // "foofoofabc"
'abc'.padStart(6,"123465"); // "123abc"
'abc'.padStart(8, "0");     // "00000abc"
'abc'.padStart(1);          // "abc"

 

19.repeat()返回指定重復次數的由元素組成的字符串對象。

"abc".repeat(-1)     // RangeError: repeat count must be positive and less than inifinity
"abc".repeat(0)      // ""
"abc".repeat(1)      // "abc"
"abc".repeat(2)      // "abcabc"
"abc".repeat(3.5)    // "abcabcabc" 參數count將會被自動轉換成整數.
"abc".repeat(1/0)    // RangeError: repeat count must be positive and less than inifinity

({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)   
//"abcabc",repeat是一個通用方法,也就是它的調用者可以不是一個字符串對象.

es6新增 

20.includes()直接用來判斷字符串是否存在

let str = 'Hello world";
console.log(str.includes('abc') // false

21.startsWith()判斷該字符串是否以searchString開頭(可以用來檢測是否是地址)

let str = 'http://www.baidu.com';
console.log(str.startsWith('http://')); // true

22.endsWith()判斷該字符串是否以searchString結尾(可以用來檢測文件擴展名)。

let str = './images/icon/login.png';
console.log(str.endsWith('.png')); // true

 


免責聲明!

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



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