在 JavaScript 中去除字符串驼峰命名
我们需要编写一个 JavaScript 函数,该函数将一个字符串作为第一个参数,并将一个分隔符作为第二个参数。
第一个字符串保证是一个驼峰方式的字符串。此函数应通过使用作为第二个参数提供的分隔符来分隔单词,从而转换字符串的大小写。
例如 −
如果输入字符串是 −
const str = 'thisIsAString'; const separator = '_';
那么输出字符串应该是 −
const output = 'this_is_a_string';
示例
以下是代码 −
const str = 'thisIsAString';
const separator = '_';
const separateCase = (str = '', separator = ' ') => {
const arr = [];
let left = 0, right = 0;
for(let i = 0; i < str.length; i++){
const el = str[i];
const next = str[i + 1];
if((el.toUpperCase() === el && el.toUpperCase() !== el.toLowerCase()) || !next){
right = i + Number(!next);
};
if(left !== right){
const sub = str.substring(left, right).toLowerCase();
arr.push(sub);
left = right;
};
};
return arr.join(separator);
};
console.log(separateCase(str, separator));输出
以下是在控制台上的输出 −
this_is_a_string
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP