javascript經常使用方法 - String

// 1.長字符串
  // 1.1
  let longString1 = "This is a very long string which needs " +
    "to wrap across multiple lines because " +
    "otherwise my code is unreadable.";
  // 1.2 反斜槓
  let longString2 = "This is a very long string which needs \
                      to wrap across multiple lines because \
                      otherwise my code is unreadable.";

  // 2.經常使用方法

  // 2.1 查找
  {
    // 2.1.1 indexOf(searchValue[, fromIndex])
    // 查找(向右):從字符串對象中返回首個被發現的給定值的索引值,若是沒有找到則返回-1。
    "Blue Whale".indexOf("Blute");    // 返回 -1
    "Blue Whale".indexOf("Whale", 0); // 返回  5
    "Blue Whale".indexOf("Whale", 3); // 返回  5 fromIndex 大於 0 且小於等於 str.length 時,返回 fromIndex;
    "Blue Whale".indexOf("Whale", 5); // 返回  5,這裏1 - 5 都返回 5

    // 2.1.2 lastIndexOf(searchValue[, fromIndex])
    // 查找(向左):從字符串對象中返回最後一個被發現的給定值的索引值,若是沒有找到則返回-1。
    'canal'.lastIndexOf('a');     // returns 3 (沒有指明fromIndex則從末尾l處開始反向檢索到的第一個a出如今l的後面,即index爲3的位置)
    'canal'.lastIndexOf('a', 2);  // returns 1(指明fromIndex爲2則從n處反向向回檢索到其後面就是a,即index爲1的位置)
    'canal'.lastIndexOf('a', 0);  // returns -1(指明fromIndex爲0則從c處向左迴向檢索a發現沒有,故返回-1)
    'abab'.lastIndexOf('ab', 2)   // returns 2 由於fromIndex只限制待匹配字符串的開頭那一個

    // 2.1.3 charAt()
    // 返回特定位置的字符。
    var charAt = 'cat'.charAt(1); // returns "a"
    console.log("charAt() 從字符串中獲取單個字符:" + charAt);

    // 2.1.4 search(regexp)
    // 對正則表達式和指定字符串進行匹配搜索,返回第一個出現的匹配項的下標。
    var str = "hey JudE";
    var re = /[A-Z]/g;
    var re2 = /[.]/g;
    console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"
    console.log(str.search(re2)); // returns -1 cannot find '.' dot punctuation


    // 2.1.5 match() 
    // 方法檢索返回一個字符串匹配正則表達式的的結果。
    // 參考正則表達式:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
  }


  // 2.2 截取
  {
    // 2.2.1 substr(start[, length])
    // 截取(不包含結束位置)
    var str = "abcdefghij";
    console.log("(1,2): " + str.substr(1, 2));   // (1,2): bc
    console.log("(-3,2): " + str.substr(-3, 2));  // (-3,2): hi = (-3+str.length,2)

    // 2.2.2 substring(indexStart[, indexEnd])
    // 截取(包含結束位置,若是 indexStart > indexEnd,則兩個參數調換)
    var anyString = "Mozilla";
    console.log(anyString.substring(0, 3)); // 輸出 "Moz"
    console.log(anyString.substring(3, 0)); // 輸出 "Moz",indexStart > indexEnd,兩個參數調換
    console.log(anyString.substring(4, 7)); // 輸出 "lla"

    // 2.2.3 slice(beginIndex[, endIndex])
    // 截取(包含結束位置,若是 indexStart > indexEnd,則兩個參數不調換)
    var strSlice = 'The quick brown fox jumps over the lazy dog.';
    var s = strSlice.slice(31); // the lazy dog.
    strSlice.slice(31, 43); // "the lazy do"
  }

 
  //2.3 判斷
  {
    //2.3.1  includes(searchString[, position])
    // 包含。
    'Blue Whale'.includes('blue'); //  false

    // 2.3.2 startsWith(searchString[, position])
    // 匹配:判斷字符串的起始位置是否匹配其餘字符串中的字符。
    var str = "To be, or not to be, that is the question.";
    str.startsWith("To be");         // true
    str.startsWith("not to be");     // false
    str.startsWith("not to be", 10); // true

    //2.3.3 endsWith()
    // 結尾:是否以給定字符串結尾,結果返回布爾值。
    var str = "To be, or not to be, that is the question.";
    str.endsWith("question.");  // true
    str.endsWith("to be");     // false
    str.endsWith("to be", 19);  // true
  }


  // 2.4 切割
  {
    // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/split
    // split([separator[, limit]])
    // @separator 能夠是一個字符串或正則表達式
    // @limit 限定返回的分割片斷數量
    // 切割:經過分離字符串成字串,將字符串對象分割成字符串數組。
    var str = 'The quick brown fox jumps over the lazy dog.';
    var words1 = str.split();
    console.log(words1);
    // ["The quick brown fox jumps over the lazy dog."]
    var words2 = str.split('');
    console.log(words2);
    //(44) ["T", "h", "e", " ", "q", "u", "i", "c",......"d", "o", "g", "."]
    var words3 = str.split(' ');
    console.log(words3);
    //(9) ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
    var words4 = str.split(' ', 3);
    console.log(words4);
    //(3) ["The", "quick", "brown"]
  }

  //2.5 填充
  {
    // 2.5.1 padStart(targetLength [, padString])
    // @targetLength 當前字符串須要填充到的【目標長度】。若是這個數值小於當前字符串的長度,則返回當前字符串自己。
    // @padString 填充字符串。若是字符串太長,超過了目標長度,則只保留最左側的部分,其餘部分會被截斷。
    // 填充(左):在當前字符串頭部填充指定的字符串, 直到達到指定的長度。 返回一個新的字符串。
    'abc'.padStart(10);         // "       abc" -- 總共長度爲10
    'abc'.padStart(10, "foo");  // "foofoofabc"
    'abc'.padStart(6, "123465"); // "123abc"
    'abc'.padStart(8, "0");     // "00000abc"
    'abc'.padStart(1);          // "abc"

    // 2.5.2 padEnd(targetLength [, padString])
    // @targetLength 當前字符串須要填充到的【目標長度】。若是這個數值小於當前字符串的長度,則返回當前字符串自己。
    // @padString 填充字符串。若是字符串太長,超過了目標長度,則只保留最左側的部分,其餘部分會被截斷。
    // 填充(右):在當前字符串尾部填充指定的字符串, 直到達到指定的長度。 返回一個新的字符串。
    'abc'.padEnd(10);          // "abc       "
    'abc'.padEnd(10, "foo");   // "abcfoofoof"
    'abc'.padEnd(6, "123456"); // "abc123"
    'abc'.padEnd(1);           // "abc" 若是這個數值小於當前字符串的長度,則返回當前字符串自己。
  }

   // 2.6 替換
   {
    // replace(regexp|substr, newSubStr|function)
    // https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace
    // @regexp (pattern)    一個RegExp 對象或者其字面量。
    // @substr(pattern)    一個將被 newSubStr 替換的 字符串。(僅第一個匹配項會被替換。)
    // @newSubStr(replacement)    用於替換掉第一個參數在原字符串中的匹配部分的字符串。該字符串中能夠內插一些特殊的變量名。
    //    替換字符串:$$,$&,$`,$',$n
    // @function (replacement)    一個用來建立新子字符串的函數,該函數的返回值將替換掉第一個參數匹配到的結果。
    //    參數:@match, p1, p2, p3, offset, string
    var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?';
    var regex = /dog/gi;   //全局替換(g)和忽略大小寫(i)
    console.log(p.replace(regex, 'ferret'));
    // expected output: "The quick brown fox jumps over the lazy [ferret]. If the [ferret] reacted, was it really lazy?"
    console.log(p.replace('dog', 'monkey'));
    // expected output: "The quick brown fox jumps over the lazy [monkey]. If the [dog] reacted, was it really lazy?"
    // 第2個括號的dog未被替換
  }

  //2.7 合併
  {
    // 強烈建議使用 賦值操做符(+, +=)代替 concat 方法。參看 性能測試(perfomance test)。
    // concat(string2, string3[, ..., stringN])
    // 合併。
    var hello = "Hello, ";
    console.log(hello.concat("Kevin", " have a nice day.")); /* Hello, Kevin have a nice day. */
  }

  //2.8 去掉空格
  {
    // trim()
    // 去除空格。
  }

  //2.9 大小寫
  {
    // 小寫。
    // 2.9.1 toLowerCase()
    // 2.9.2 toLocaleLowerCase()

    // 大寫。
    // 2.9.3 toUpperCase()
    // 2.9.4 toLocaleUpperCase()
  }
相關文章
相關標籤/搜索