js——replace (駝峯式命名規則轉換)

駝峯式命名規則轉換

function camelize(str) {
    return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : '')
}

console.log(camelize('hello-world')); // helloWorld
function capitalize(str) {
    return str.replace(/\B([A-Z])/g, '-$1').toLowerCase()
}

console.log(capitalize('HelloWorld')) // hello-world

replace

stringObject.replace(regexp/substr,replacement)

正則快速直通車

replacement 可以是字符串,也可以是函數。如果它是字符串,那麼每個匹配都將由字符串替換。但是 replacement 中的 $ 字符具有特定的含義。如下表所示,它說明從模式匹配得到的字符串將用於替換。

字符 替換文本
$1、$2、…、$99 與 regexp 中的第 1 到第 99 個子表達式相匹配的文本。
$& 與 regexp 相匹配的子串。
$` 位於匹配子串左側的文本。
$’ 位於匹配子串右側的文本。
$$ 直接量符號。

replace() 方法的參數 replacement 可以是函數而不是字符串。在這種情況下,每個匹配都調用該函數,它返回的字符串將作爲替換文本使用。該函數的第一個參數是匹配模式的字符串。接下來的參數是與模式中的子表達式匹配的字符串,可以有 0 個或多個這樣的參數。接下來的參數是一個整數,聲明瞭匹配在 stringObject 中出現的位置。最後一個參數是 stringObject 本身。

例子:

name = "Doe, John";
name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"); // John Doe
name = '"a", "b"';
name.replace(/"([^"]*)"/g, "'$1'"); // 'a', 'b'
name = 'aaa bbb ccc';
name.replace(/\b\w+\b/g, function (word) {
    return word.substring(0, 1).toUpperCase() + word.substring(1);
}); // Aaa Bbb Ccc
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章