Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第4天 写一个方法把下划线命名转成大驼峰命名 #12

Open
haizhilin2013 opened this issue Apr 19, 2019 · 182 comments
Open
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第4天 写一个方法把下划线命名转成大驼峰命名

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 19, 2019
@undefinedYu
Copy link
Contributor

function changeLine (str) {
if(typeof str !== 'string'){
alert('请确认要删除的对象为字符串!');
}else {
var newName = '';
var arr = str.split('_');
arr.map((v,i)=>{
if(i===0){return};
newName += ad.substr(0,1).toUpperCase() + ad.substr(1);
})
}
}

@Mr-mi
Copy link

Mr-mi commented May 6, 2019

function changeLine(str){
if(typeof str!=='string'){
alert('Please确认要删除的对象为字符串!');
} else {
var newName ='';
var arr = str.split('_');
arr.map((v,i)=> {
if(i === 0){return};
newName + = ad.substr(0,1).toUpperCase()+ ad.substr(1);
})
}
}

function changeLine(str) {
if (typeof str !== 'string') {
alert('请确认要删除的对象为字符串!');
} else {
var newName = '';
var arr = str.split('_');
// console.log(arr)
arr.map((v, i) => {
if (i === 0) { return aa=v};
newName += aa+v.substr(0, 1).toUpperCase() + v.substr(1);
})
return newName
}
}

@linghucq1
Copy link

function toCamel(str) {
  return str.replace(/(\w)(_)(\w)/g, (match, $1, $2, $3) => `${$1}${$3.toUpperCase()}`)
}

console.log(toCamel('a_bc_def')) // aBcDef 

@linghucq1
Copy link

linghucq1 commented May 8, 2019

上面的方法对 a_c_def 会返回 aC_def,想要返回 ACDef 得:

function toCamel(str) {
  str = str.replace(/(\w)/, (match, $1) => `${$1.toUpperCase()}`)
  while(str.match(/\w_\w/)) {
    str = str.replace(/(\w)(_)(\w)/, (match, $1, $2, $3) => `${$1}${$3.toUpperCase()}`)
  }
  return str
}

console.log(toCamel('a_c_def')) // ACDef 

@coderfe
Copy link

coderfe commented May 8, 2019

function toCamelCase(str) {
  if (typeof str !== 'string') {
    return str;
  }
  return str
    .split('_')
    .map(item => item.charAt(0).toUpperCase() + item.substr(1, item.length))
    .join('');
}

@lantian1024
Copy link

function toCamel(str) {
    str = str.replace(/_(\w)/g, (match, $1) => `${$1.toUpperCase()}`)
    return str.substr(0,1).toUpperCase() + str.substr(1);
}

console.log(toCamel('a_bc_def'))

@qqdnnd
Copy link

qqdnnd commented May 16, 2019

function strToCamel(str){
    return str.replace(/(^|_)(\w)/g,(m,$1,$2)=>$2.toUpperCase());
}

@douxiaohou
Copy link

let str = 'hello_word'

function capital(str) {
let s = str
if(typeof s !== 'string'){
alert('类型不对哦~')
}
let arrStr = s.split('_')
let newStr = ''

arrStr.forEach((v,i)=>{
	if(v == ''){
		arrStr.splice(i,1) // 筛选掉空 如:hello_
	}
	newStr = newStr + v.substr(0,1).toUpperCase() + v.substr(1)
})

return newStr

}

console.log(capital(str)) // HelloWord

@likeke1997
Copy link

function transoform(str) {
    var result = str.split('');
    result.forEach(function(e, i, a) {
        if (e === '_') { a[i + 1] = a[i + 1].toUpperCase(); }
    });
    return result.join('').replace(/\_*/g, '');
}
var result = transoform('if_you_are_my_world');
console.log(result); // ifYouAreMyWorld

@myprelude
Copy link

 function changeStr(str){
   if(str.split('_').length==1)return;
   str.split('_').reduce((a,b)=>{
     return a+b.substr(0,1).toUpperCase() + b.substr(1)
   })
}

@abin-jb
Copy link

abin-jb commented Jun 13, 2019

function capitalize(str) {
const camelizeRE = /(\w)/g
return str.replace(camelizeRE, (
, c) => c? c.toUpperCase():'')
}

@Damon99999
Copy link

Damon99999 commented Jun 18, 2019

var str= "aaa_bbb_ccc"
function traHump(str) {
    var reg = /^[_a-zA-Z]+$/;
    if (typeof str !== "string" || !reg.test(str)) return;
    var newArr = [];
    var arr = str.split("");
    arr.forEach((item, index) => {
        if (item !== "_") {
		newArr.push(item);
        } else {
                newArr.push(arr[index+1].toUpperCase());
        }
    })
    console.log(newArr.join(""));	
}
traHump(str);

// 此情况未考虑:___a____

@khhh97
Copy link

khhh97 commented Jun 30, 2019

function transoform(str) {
    var result = str.split('');
    result.forEach(function(e, i, a) {
        if (e === '_') { a[i + 1] = a[i + 1].toUpperCase(); }
    });
    return result.join('').replace(/\_*/g, '');
}
var result = transoform('if_you_are_my_world');
console.log(result); // ifYouAreMyWorld

有一个小问题,当str以 _ 结尾的时候,不存在 a[i+1]

@xuxusheng
Copy link

function snakeToCamel(str: string) {
  const s = str
    .split('_')
    .filter(v => !!v)
    .map(v => v[0].toUpperCase() + v.substr(1))
    .join('');
  return s[0].toLowerCase() + s.substr(1);
}

@Konata9
Copy link

Konata9 commented Jul 1, 2019

const toCamel = str =>
  str
    .split("_")
    .filter(s => !!s)
    .map((s, index) => (index === 0 ? s : s[0].toUpperCase() + s.slice(1)))
    .join("");

console.log(toCamel("a_bc_d"));
console.log(toCamel("bc_d"));
console.log(toCamel("bc___________ed"));
console.log(toCamel("_______a_bc_d__"));

// 顺便写的驼峰转下划线
const toSnake = str => {
  const target = str[0].toLowerCase() + str.slice(1);
  let result = target;
  (target.match(/[A-Z]/g) || []).forEach(word => {
    result = result.replace(word, `_${word.toLowerCase()}`);
  });
  return result;
};

console.log(toSnake("aBcDeFg"));
console.log(toSnake("ABCDEFG"));

@TKBnice
Copy link

TKBnice commented Jul 1, 2019

console.log(changeHump('aewq_a_rgt____eryry'))
function changeHump(str){
if(typeof str !== 'string'||str.split('').length===1) return str;
return (str.split('
').filter(s => !!s).map(e=>(e.substr(0, 1).toUpperCase()+e.substr(1)))).join('');
}

@zzccww
Copy link

zzccww commented Jul 2, 2019

	function func(str){
		return str.replace(/(_)([a-z])/g,function(rs){ 
			 return arguments[2].toUpperCase()
			 }
		)
	}

func("a_c_def")

@15190408121
Copy link

献丑了,通过去掉下划线和空格的方式进行实现
var underline = "safaf_asd___cddaa_________ssa"
function underlines(und) {
let unds = und
let a = 0
let joint = ""
unds = unds.split("_")
for (let i = 0; i < unds.length; i++) {
if (unds[i] !== "") {
if (a === 0) {
joint += unds[i]
a++
} else if (a > 0) {
// charAt() 方法可返回指定位置的字符
// toUpperCase() 方法用于把字符串转换为大写
// slice(),返回一个新的数组,该方法可从已有的数组中返回选定的元素
joint += unds[i].charAt(0).toUpperCase() + unds[i].slice(1)
}
}
}
return joint
}
underlines(underline)

@Makcy
Copy link

Makcy commented Jul 4, 2019

(str) => str.split('_').reduce((acc, cur) => acc + cur.slice(0,1).toUpperCase() + cur.slice(1))

@richard1015
Copy link

var resstr = "";
"html___accc_ddddd".split('_').forEach(element => {
    if (element)
        resstr += element[0].toUpperCase() + element.substring(1, element.length);
})
console.log(resstr)

@Azathoth-H
Copy link

Azathoth-H commented Jul 12, 2019

const changeStr = (str) => {
      if(typeof str != 'string') return 'go away'
      let _str = str.replace(/__+/g, '_') // '_what_the_f**k_'
      if (_str.startsWith('_')) _str = _str.substr(1, _str.length) // 'what_the_f**k_'
      if (_str.endsWith('_')) _str = _str.substr(0, _str.length - 1) // 'what_the_f**k'
      return _str.split('_').reduce((acc, x) => acc + x[0].toUpperCase() + x.substr(1))
    }
    changeStr('_what______the_f**k__')

@seho-dev
Copy link

seho-dev commented Jul 14, 2019

function lineChangeUpper(str) {
if (typeof str !== "string") {
throw new Error("非字符串");
} else {
let test_arr = str.split("");
if (str.indexOf("
") > 0) {
for (let key in test_arr) {
if (key > 0) {
test_arr[key] =
test_arr[key][0].toUpperCase() +
test_arr[key].substr(1);
}
}
return test_arr.join("");
} else {
throw new Error("没有下划线");
}
}
}

let str = "up_set_to";
console.log(lineChangeUpper(str));

不太明白那些写那么复杂的有啥用???笔试题会让你写这么复杂的,越短小易懂越好;
哈哈,开个玩笑,你们写的好秀,面试官会眼前一亮,牛逼

@shufangyi
Copy link

const underlineToBigHump = str =>
  typeof str === 'string'
    ? str
        .split('_')
        .map(item => item.toLocaleLowerCase())
        .reduce(
          (pre, item) =>
            item ? `${pre}${item[0].toLocaleUpperCase()}${item.slice(1)}` : pre,
          ''
        )
    : str

@NicholasBaiYa
Copy link

function uChangeH(str){ let arr = str.split("_") let newArr = arr.map((e,index)=> { if(index >0){ e = e[0].toLocaleUpperCase() + e.slice(1,e.length); } return e }) return newArr.join(""); }

@wyx2014
Copy link

wyx2014 commented Jul 24, 2019

function change2Letter(str) { if(typeof str !== 'string'){ return '请输入字符串' } return /[0-9a-zA-Z\$]+\_/.test(str)?str.split('_').map(function (item,index) { return index === 0 ? item:item.substring(0,1).toUpperCase() + item.substring(1); }).join(''):str; }

@gu-xionghong
Copy link

function toCamelCase(str) {
  return str.replace(/_(\w)/g, function(m, $1) {
    return $1 ? $1.toUpperCase() : m
  })
}

toCamelCase('_a_b_c__')

@IanSun
Copy link

IanSun commented Jul 26, 2019

function snakeToCamel ( string = `` ) {
  return string.replace( /\u005f([\u0061-\u007a])/gu, ( match, char ) => char.toUpperCase() );
}

@wsb260
Copy link

wsb260 commented Jul 31, 2019


// 1.传入参数,判断字符串类型,非返回
// 2.通过split('_')把字符串分割成数组
// 3.遍历数组把每一项开头转换成大写字母,并把每一项都拼接到一起
// 4.返回字符串
function changeStr(str){
  let arr = [];
  let newStr = '';
  if(!str||str===' '|| typeof str !== 'string'){
    return false;
  }
 arr = str.split('_');
 arr.map(item => {
   if(item){ //过滤空字符
      newStr += item.substr(0,1).toUpperCase()+item.substr(1)
   }
 });
 console.log(newStr);
}
changeStr('_abc_ghe_nb_w_') // 输出:AbcGheNbW

@tigermmmmm
Copy link

tigermmmmm commented Jul 31, 2019

function changeStr(str){
var newName = '';
var arr = str.split('_');
var first = arr[0];
if(arr.length == 1){
console.log(first)
}else{
for(var i=1;i<arr.length;i++){
newName += arr[i].charAt(0).toUpperCase() + arr[i].substr(1,arr[i].length)
if(i==arr.length-1){
console.log(first+newName)
}
}
}
}

changeStr("add_ffff_dd")

@sup194
Copy link

sup194 commented Feb 22, 2022

const switchUpperDump = (str) => {
return str.spilt('_')
.map(item => item.charAt(0).toUpperCase() + item.substr(1))
.join('')
}

@wind8866
Copy link

wind8866 commented Mar 3, 2022

const camelCase = (str) => {
  return str.replace(/^([a-z])|_([a-z])/g, (str, subStr1, subStr2) => {
    return subStr1 ? subStr1.toUpperCase() : subStr2.toUpperCase()
  })
}
camelCase('user_name')
camelCase('user_first_name')

@yxllovewq
Copy link

yxllovewq commented Mar 7, 2022

// _2c:小驼峰命名,_2c_big:大驼峰命名
const _2c = (str = '') => str.replace(/(_)(?<!^_)(\w)/g, (...res) => res[2].toUpperCase());
const _2c_big = (str = '') => _2c(str).replace(/\w/, char => char.toUpperCase())

@jake-yu
Copy link

jake-yu commented May 12, 2022 via email

@kankan-web
Copy link

function changeName2(chars:string):string{
  return chars.split('_').map((item,index)=>{
    if(index===0) return item;
    return item.slice(0,1).toLocaleUpperCase()+item.slice(1)
  }).join('')
}
console.log('1',changeName2('age_name_sex'))

@vesere
Copy link

vesere commented May 15, 2022

function splstr(str){
let s = str
let arr = s.split('_')
var newstr = ''
arr.forEach((v,i)=>{
// 判断是否含有空格 也就是在结尾或者在前面有下划线
if(v==""){
arr.splice(i,1)
}
newstr = newstr + v.substr(0,1).toUpperCase() + v.substr(1)
})
return newstr
}

console.log(splstr('name_io_ds_'));// NameIoDs

@mutunx
Copy link

mutunx commented May 18, 2022

function fn(name) {
    if (typeof name !== 'string' || !name.includes('_')) return name;
    let arr = name.split('_'); 
    arr = arr.filter(x=>x!=='').map(x=>x[0].toUpperCase() + x.substring(1, ));
    return arr.join('') === "" ? name:arr.join('');
}

@wenxd
Copy link

wenxd commented May 18, 2022

       function underLineToHump(str) {
		let strArr = str.split('_')
		let humpstr = ''
		strArr.map((item) => {
			humpstr += item.charAt(0).toUpperCase() + item.slice(1)
		})
		console.log(humpstr);
	}
	underLineToHump('get_user_list')

@xiaoqiangz
Copy link

// 将-转出大驼峰字符
let str2 = 'kk_aa_bb_cc_dd_ee_fff'
function lineToUpperCase(str) {
let arr = str.split('_')
if (arr.length <= 0) {
throw new Error('字符串异常')
}
let newStr = ''
arr.forEach(item => {
newStr += item.slice(0, 1).toUpperCase() + item.slice(1)
})
return newStr
}
console.log(lineToUpperCase(str2))

@xiaoxiaozhiya
Copy link

var str="defrg_dede_you_shi"
function toTuoName(str){
var arrTran=str.split("") //将原字符串转为数组处理
arrTran.forEach(function(element,index) {
if(element==='_'){
var element=arrTran.at(index+1) //获取字符串
var newElement=element.toUpperCase() //把字符串转为大写
arrTran.splice(index,1,newElement)
// console.log(arrTran)
}
});
// console.log(arrTran.join(''))
return arrTran.join('')
}

    console.log(toTuoName(str))

我自己是转换成了一个单个的字符数组

  1. 将string转为字符数组,str.split("")
  2. 使用forEach遍历每一项
  3. 用arr.at()获取"_"后一项字符
  4. 将字符转换为大写,str.toUpperCase()
  5. 用arr.splice(index,count,newElement)替换“_”
  6. 返回转换为字符串的数组,arr.join("")

可借鉴的方法

直接使用_分割成数组,处理数组的第一个元素为大写字母,更加方便

@YJH94
Copy link

YJH94 commented Jun 17, 2022

				let str = "a_b_cdef_ef";
				let ary = str.split("_").map((item, index) => {
					if (index != 0) {
						let char = item.charAt(0).toUpperCase();
						item = char + item.substring(1);
					}
					return item;
				})
				console.log(ary.join(''));										

@jake-yu
Copy link

jake-yu commented Jun 17, 2022 via email

@www-wanglong
Copy link

'ak_das_sda'.replace(/(^|_)(\w)/g, (match, $1, $2) => $2.toUpperCase())

@WangXi01
Copy link

function toCamelCase(str) {
  if (typeof str !== 'string') {
    return str;
  }
  return str
    .split('_')
    .map(item => item.charAt(0).toUpperCase() + item.substr(1, item.length))
    .join('');
}

@jake-yu
Copy link

jake-yu commented Jul 12, 2022 via email

@wyy-g
Copy link

wyy-g commented Sep 7, 2022

function changeStr(str){
var reg = /_[a-z]/g;
return str.replace(reg, function(match, $1){
return $1.toUpperCase()
})
}

@jake-yu
Copy link

jake-yu commented Sep 7, 2022 via email

@GitHubJiKe
Copy link

image

@jake-yu
Copy link

jake-yu commented Sep 29, 2022 via email

@wl2282589971
Copy link

function toCamelCase(str) {
var arr = str.split("_");
for (var i = 1; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
}
return arr.join("");
}

@Hanies11
Copy link

正好把之前的递归和去掉最后一个指定字符 用到的方法结合起来

function formatting(str, ref) {
let i = str.indexOf(ref);
if (i == -1) return str;
let newStr = str.slice(0, i) + str[i + 1].toUpperCase() + str.slice(i + 2, str.length)
return str.indexOf(ref) == -1 ? newStr : formatting(newStr, ref)
}
console.log(formatting('a_bad_csa', '_'))

@jake-yu
Copy link

jake-yu commented Mar 10, 2023 via email

@Hanies11
Copy link

正好把之前的递归和去掉最后一个指定字符 用到的方法结合起来

function formatting(str, ref) { let i = str.indexOf(ref); if (i == -1) return str; let newStr = str.slice(0, i) + str[i + 1].toUpperCase() + str.slice(i + 2, str.length) return str.indexOf(ref) == -1 ? newStr : formatting(newStr, ref) } console.log(formatting('a_bad_csa', '_'))

复习
const hump = (str, char = '_') => str.split(char).map((v, i) => i == 0 ? v : v[0].toUpperCase() + v.slice(1, v.length)).join("")
console.log(hump("ha_ha_ha"))

@yougexiaobaobei
Copy link

let str = "my_name_is_liuyu"
function change(str) {
let newstr = str.split("")
for (let i = 0; i < newstr.length; i++) {
if (newstr[i] === "") {
newstr[i + 1] = newstr[i + 1].toUpperCase()
}
}
newstr = newstr.filter(item => {
return item !== "
"
})
return newstr.join("")
}
console.log(change(str));

@13714273163
Copy link

13714273163 commented Dec 3, 2023 via email

@jake-yu
Copy link

jake-yu commented Dec 3, 2023 via email

@lili-0923
Copy link

function transform(str) {
return str
.split("_")
.map((item, index) =>
index > 0 && item
? item && item[0].toLocaleUpperCase() + item.slice(1)
: item
)
.join("");
}

@jake-yu
Copy link

jake-yu commented Feb 2, 2024 via email

@usercci
Copy link

usercci commented Mar 5, 2024

const toCamelCase = (string) => {
      const stringSplits = string.split("_");
      if (stringSplits.length === 1) {
        console.log(stringSplits);
        return string;
      }
      const results = stringSplits.reduce((pre, cur, index) => {
        if (index === 0) {
          return pre + cur;
        } else {
          return pre + cur.charAt(0).toUpperCase() + cur.slice(1);
        }
      }, "");
      return results;
    };
    const result = toCamelCase("camel_case");

@jake-yu
Copy link

jake-yu commented Mar 5, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests