JavaScript 中连字符字符串转换为驼峰式字符串

javascriptweb developmentobject oriented programmingfront end technology更新于 2026/1/16 15:08:17

假设我们有一个字符串,其中包含用连字符分隔的单词,例如 −

const str = 'this-is-an-example';

我们需要编写一个 JavaScript 函数,该函数接受一个这样的字符串并将其转换为驼峰式字符串。

对于上述字符串,输出应为 −

const output = 'thisIsAnExample';

其代码为 −

const str = 'this-is-an-example';
const changeToCamel = str => {
   let newStr = '';
   newStr = str
   .split('-')
   .map((el, ind) => {
      return ind && el.length ? el[0].toUpperCase() + el.substring(1)
      : el;
   })
   .join('');
   return newStr;
};
console.log(changeToCamel(str));

以下是控制台上的输出 −

thisIsAnExample

相关文章


有用资源