注意: 規范中規定 toFixed() 方法可以表示帶有 0 ~ 20 個小數位的數值,但有的瀏覽器支持更多位數。
注意: 規范中規定 toPrecision() 方法可以表示帶有 1 ~ 21 個小數位的數值,但有的瀏覽器支持更多位數。
這些方法對原始字符串沒有影響,如果沒有給這些方法傳遞第二個參數,就會將字符串的長度作為結束位置。
方法名 | 接受參數 | 說明 |
---|---|---|
slice() | 字符串開始位置、子字符串最后一個字符后面的位置(可選) | 如果參數是負數,會將負值與字符串的長度相加 |
substring() | 字符串開始位置、子字符串最后一個字符后面的位置(可選) | 將所有的負值轉換為 0 |
substr() | 字符串開始位置、需要返回的字符個數(可選) | 負的第一個參數加上字符串長度,負的第二個參數轉換為 0 |
字符序列 | 替換文本 |
---|---|
$$ | $ |
$& | 匹配整個模式的子字符串(與 RegExp.lastMatch 的值相同) |
$’ | 匹配的子字符串之前的子字符串(與 RegExp.leftContext 的值相同) |
$` | 匹配的子字符串之后的子字符串(與 RegExp.rightContext 的值相同) |
$n | 匹配第 n 個捕獲組的子字符串。n 為 0 ~ 9。如果正則表達式沒有定義捕獲組,則使用空字符串 |
$nn | 匹配第 nn 個捕獲組的子字符串。n 為 01 ~ 99。如果正則表達式沒有定義捕獲組,則使用空字符串 |
* 使用特殊的字符序列,可以使用最近一次匹配結果中的內容:
var text = "cat,bat,sat,fat";result = text.replace(/(.at)/g, "Word ($1)");console.log(result);//word (cat),word (bat),word (sat),word (fat)replace() 的第二個參數也可以是函數。在只有一個匹配項的情況下,會向這個函數傳遞 3 個參數:模式的匹配項、模式匹配項在字符串中的位置以及原始字符串。在正則表達式中定義了多個捕獲組的情況下,傳遞給函數的參數依次是模式的匹配項、第一個捕獲組的匹配項、第二個捕獲組的匹配項……,最后兩個參數是模式匹配項在字符串中的位置以及原始字符串。因此這個函數可以實現更加精細的替換操作:function htmlEscape(text) { return text.replace(/[<>"&]/g, function (match, pos, originalText) { switch (match) { case "<": return "<"; case ">": return ">"; case "&": return "&"; case "/"": return """; } }); } console.log(htmlEscape("<p class=/"greeting/">Hello world!</p>"));//<p class="greeting">Hello world!</p>split() 基于指定的分隔符將一個字符串分割成多個子字符串,并將結果放入數組中。分隔符可以是字符串或者 RegExp 對象。她還接受第二個參數,用于指定數組的大小:var colorText = "red,blue,green,yellow";console.log(colorText.split(","));console.log(colorText.split(",", 2));console.log(colorText.split(/[^/,]+/));對 split() 中正則表達式的支持因瀏覽器而異,因此在使用時,一定要在各種瀏覽器下做一做測試。比較兩個字符串,并返回: * 如果字符串在字母表中排在字符串參數之前,則返回負數。 * 如果字符串等于字符串參數,則返回 0。 * 如果字符串在字母表中排在字符串參數之后,則返回正數。
var stringValue = "yellow";console.log(stringValue.localeCompare("brick"));//1console.log(stringValue.localeCompare("yellow"));//0console.log(stringValue.localeCompare("zoo"));//-1因為 localeCompare() 返回的數值取決于實現,因此最好這樣使用: function determineOrder(value) { var result = stringValue.localeCompare(value); if (result < 0) { console.log("The string 'yellow' comes before the string '" + value + "'."); } else if (result > 0) { console.log("The string 'yellow' comes after the string '" + value + "'."); } else { console.log("The string 'yellow' is equal to the string '" + value + "'."); } } determineOrder("brick"); determineOrder("yellow"); determineOrder("zoo");localeCompare() 所支持的地區決定了這個方法的行為。在美國地區,localeCompare() 是區分大小寫的,因此大寫字母排在小寫字母前是一個決定性的比較規則。其他地區就不一定了,要測試過了才知道哦 O(∩_∩)O~
接收一或者多個字符編碼,然后轉換為字符串。她是與 charCodeAt() 相反的操作:
console.log(String.fromCharCode(104, 101, 108, 108, 111));//hello有些瀏覽器擴展了標準,實現了一些專門用于簡化 HTML 格式化任務的方法。最好不要使用,因為它們創建的標記通常無法表達語義,而且不通用,所以這里就不詳細列出了哦 O(∩_∩)O~
新聞熱點
疑難解答