我们需要编写一个JavaScript函数,该函数将字符串作为第一个参数,并将分隔符作为第二个参数。
确保第一个字符串是camelCased字符串。该函数应通过使用作为第二个参数提供的分隔符分隔单词来转换字符串的大小写。
例如-
如果输入字符串是-
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