![](/img/trans.png)
[英]How can I convert string “folder/lower-case-with-dash” to “folderLowerCaseWithDash” (i.e. to camelCase format) using regex?
[英]How to convert string to camelCase without using RegEX
我正在尝试将所有字符串转换为 camelCase 但不使用正则表达式,仅使用(拆分、切片、替换、包含等)之类的方法。 有些单词有空格,应该删除它们。 这是代码,我真的很困惑。 注意:用户输入 STRING,当用户单击按钮时,应返回 camelCase。
INPUT => //underscore_case
//first_name
//Some_Variable
// calculate_AGE
//delayed_departure
OUTPUT => //underscoreCase
//firstName
//someVariable
//calculateAge
//delayedDeparture
document.body.append(document.createElement('textarea'));
document.body.append(document.createElement('button'));
document.querySelector('button').addEventListener('click', function() {
const text = document.querySelector('textarea').value;
const row = text.split('\n');
let [...n] = '';
for (const theText of row) {
const lowerText = theText.toLowerCase().trim();
if (lowerText.includes('_')) {
n = lowerText.replace('_', ' ');
console.log([...n]);
}
}
});
这个简单算法的解释:
您的输入必须包含被某个字符分割的单词,因为您需要一些东西来识别字符串的哪一部分是单词。 假设您的字符串中的单词由“//”分隔,而不是您在评论中提到的空格,并且每个单词都由“_”分隔。
首先,您需要将字符串中的所有单词拆分为一个数组,您可以使用split()方法来执行此操作。
然后在遍历每个单词时,使用split()
再次拆分它,但这次使用标识不同单词的任何内容,在我们的例子中是_
。
遍历每个拆分的单词,如果它是第一个单词,则使用toLowerCase()
将其小写并将其添加到新单词变量中,如果不是,则将其小写并将第一个字母大写。
就是这样。 这是实现:
const inputWithoutCamelCase = 'hello_world // HOW_ARE_YOU // foo_BAR' function stringToCamelCase(string) { const allNames = string.split('//') let camelCasedString = ''; for (const name of allNames) { camelCasedString += nameToCamelCaseHelper(name); } return camelCasedString; } function nameToCamelCaseHelper(word) { const splittedName = word.split('_'); let camelCasedName = ''; for (let i = 0; i < splittedName.length; i++) { if (i === 0) { camelCasedName += splittedName[i].toLowerCase(); } else { camelCasedName += capitalizeFirstLetter(splittedName[i].toLowerCase()) } } return camelCasedName; } function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() + string.slice(1); } stringToCamelCase(inputWithoutCamelCase) // helloWorld howAreYou fooBar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.