本文概述
- 骆驼化
- 反糖化
骆驼化以下驼峰函数将要驼峰化的文本作为第一个参数。如你所知, 字符串可以用单个空格, 下划线和连字符分隔, 因此camelize函数将自动将它们全部转换:
/**
* Camelize a string, cutting the string by multiple separators like
* hyphens, underscores and spaces.
*
* @param {text} string Text to camelize
* @return string Camelized text
*/
function camelize(text) {
return text.replace(/^([A-Z])|[\s-_]+(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
}
以下示例显示了camelize函数的结果:
// someDatabaseFieldName
console.log(camelize("some_database_field_name"));
// someLabelThatNeedsToBeCamelized
console.log(camelize("Some label that needs to be camelized"));
// someJavascriptProperty
console.log(camelize("some-javascript-property"));
// someMixedStringWithSpacesUnderscoresAndHyphens
console.log(camelize("some-mixed_string with spaces_underscores-and-hyphens"));
反糖化在反糖化过程中, 你需要将要反糖化的驼峰式情况下的字符串作为第一个参数提供给反糖化功能, 作为第二个参数, 将用于分隔每个驼峰词的分隔符:
/**
* Decamelizes a string with/without a custom separator (underscore by default).
*
* @param str String in camelcase
* @param separator Separator for the new decamelized string.
*/
function decamelize(str, separator){
separator = typeof separator === 'undefined' ? '_' : separator;
return str
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
.toLowerCase();
}
除霜的例子:
// some database field name (separate with an empty space)
console.log(decamelize("someDatabaseFieldName", " "));
// some-label-that-needs-to-be-camelized (separate with an hyphen)
console.log(decamelize("someLabelThatNeedsToBeCamelized", "-"));
// some_javascript_property (separate with underscore)
console.log(decamelize("someJavascriptProperty", "_"));
【如何在JavaScript中对字符串进行驼峰化和脱峰处理】编码愉快!
推荐阅读
- 如何在Ubuntu 16.04中使用命令行CLI安装ClamAV并扫描病毒
- JavaScript异常在Google Chrome中的含义为”不允许将顶部框架导航到数据URL(”)
- 如何安装和使用Exa,这是Ubuntu 16.04中ls命令的现代替代品
- 如何在dhtmlxScheduler中更改事件的默认长度(持续时间)
- 如何使用纯JavaScript或jQuery在客户端对表进行排序
- 如何使用MathCalc在JavaScript中实现基本的数学表达式计算器
- 讯飞输入法运用小技巧总结
- 讯飞输入法运用账户备份词库办法
- 讯飞输入法怎样设置为手机默认输入法