转换字符串string为驼峰写法

本文详细介绍了如何使用JavaScript实现字符串到驼峰命名的转换。通过分析代码,我们了解到该过程涉及字符串的分解、拉丁字母的标准化、首字母的大写转换等步骤。此技术在编程中用于变量名和函数名的规范化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 转换字符串string为驼峰写法
 * Converts `string` to [camel case]
 * @param {string} [string=''] The string to convert
 * @returns {string} Returns the camel cased string
 * @example
 * camelCase('Foo Bar')
 * // => fooBar
 * camelCase('--foo-bar--')
 * // => fooBar
 * camelCase('__FOO_BAR__')
 * // => fooBar
 */

import capitalize from "./capitalize" // 我的博客搜索【转换字符串string的首字母为大写】
import words from "./words" //我的博客搜索【拆分字符串string中的词变为数组】
import deburr from "./deburr" //我的博客搜索【转换字符串string中拉丁语-1补充字母和拉丁语扩张字母-A为基本的拉丁字母,并且去除组合变音标记】

/**
 * A specialized version of `reduce` for arrays
 * @param {Array} [array] The array to iteratee over.
 * @param {Function} iteratee The function invoked per iteration
 * @param {*} [accumulator] The initial value
 * @param {boolean} [initAccum] Specify using the first element of `array` as the initial value
 * @returns {*} Returns the accumulated value
 */
function arrayReduce(array, iteratee, accumulator, initAccum) {
  var index = -1,
    length = array == null ? 0 : array.length

  if (initAccum && length) {
    accumulator = array[++index]
  }
  while (++index < length) {
    accumulator = iteratee(accumulator, array[index], index, array)
  }
  return accumulator
}

// Used to match apostrophes.
var rsApos = "['\u2019]"
var reApos = new RegExp(rsApos, "g")

function createCompounder(callback) {
  return function(string) {
    return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "")
  }
}

var camelCase = createCompounder(function(result, word, index) {
  word = word.toLowerCase()
  return result + (index ? capitalize(word) : word)
})

export default camelCase

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值