Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

javascript - 尝试转换为驼峰式时,toUpperCase无法在for循环中工作(toUpperCase not working in for loop when trying to convert to camel case)

I looked at some other questions, haven't found one specific to this issue.(我查看了其他一些问题,但尚未找到特定于此问题的问题。)

Here is what I have:(这是我所拥有的:) function toCamelCase(str){ const _str = str.split(/-|_/) for (let i = 0; i < _str.length; i++) { // if first character of string is capital, // make it Pascal Case, not Camel Case if (i === 0) { _str[i][0] = _str[i][0].match(/[A-Z]/) ? _str[i][0].toUpperCase() : _str[i][0].toLowerCase() } else { _str[i][0] = _str[i][0].toUpperCase() } } return _str.join("") } toCamelCase("This-is_a_test-string") // Thisisateststring The output should be ThisIsATestString , but for some reason it is not working.(输出应该是ThisIsATestString ,但是由于某种原因它不起作用。) What's weird is that the first if (i === 0) .. enters and assigns properly, but the rest doesn't work, even though it is entered.(奇怪的是,第一个if (i === 0) ..正确输入和分配,但是其余的即使输入也不能正常工作。)   ask by Mike K translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not use a replacement with a function for a single letter?(为什么不对单个字母使用功能替换呢?)

const toCamelCase = string => string.replace(/[_\-](.)/g, (_, g) => g.toUpperCase()); console.log(toCamelCase("This-is_a_test-string"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...