![](/img/trans.png)
[英]What is the best way convert object keys from snake case to camel case and vice versa?
[英]Transform a string from camel case to snake case and vice versa
我想將大寫字符串轉換為帶下划線的字符串,例如:
- "blablaBlabla" to "blabla_blabla"
- "firstName" to "first_name"
反過來:
- "blabla_blabla" to "blablaBlabla"
- "first_Name" to "firstName"
我用的是Typescript,不過我覺得和Javascript沒什么區別。
提前致謝。
傑里米。
您可以使用[AZ]
獲取所有大寫字母,並使用_ + m.toLowerCase()
replace
匹配項
要以另一種方式更改它,請匹配所有_([az])
以將字母表添加到捕獲組中。 然后在捕獲上使用toUpperCase
function trasnform1(str) { return str.replace(/[AZ]/g, (m) => '_' + m.toLowerCase()) } function trasnform2(str) { return str.replace(/_([az])/g, (m, p1) => p1.toUpperCase()) } console.log(trasnform1("blablaBlabla")) console.log(trasnform1("firstName")) console.log(trasnform2("blabla_blabla")) console.log(trasnform2("first_name"))
let word = "firstName"; let output = ""; // for conversion for (let i = 0; i < word.length; i++) { if (word[i] === word[i].toUpperCase()) { output += "_" + word[i].toLowerCase(); } else { output += word[i]; } } console.log(output); let source = output; output = ""; //for reversion for (let i = 0; i < source.length; i++) { if (source[i] === "_") { i++; output += source[i].toUpperCase(); } else { output += source[i]; } } console.log(output);
// Camel to snake and snake to camel case
function changeCasing(input) {
if (!input) {
return '';
}
if (input.indexOf('_') > -1) {
const regex = new RegExp('_.', 'gm');
return input.replace(regex, (match) => {
const char = match.replace("_", "");
return char.toUpperCase();
});
} else {
const regex = new RegExp('[A-Z]', 'gm');
return input.replace(regex, (match) => {
return `_${match.toLowerCase()}`;
});
}
}
這是在 TypeScript 中編寫的示例。使用方法鏈接更具可讀性。
export const snake2Camel = (snake: string): string => {
return snake.split('').reduce((prev: string, cur: string) => {
if (prev.includes("_")) {
prev = prev.substring(0, prev.length - 1);
cur = cur.toUpperCase();
}
return prev + cur;
}, "");
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.