在 JavaScript 中对字符串进行反驼峰化

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/22 1:48:17

我们需要编写一个 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

相关文章


有用资源