驼峰式命名规则转换
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