在 JavaScript 中去除字串駝峰命名
我們需要編寫一個 JavaScript 函式,該函式將一個字串作為第一個引數,並將一個分隔符作為第二個引數。
第一個字串保證是一個駝峰方式的字串。此函式應透過使用作為第二個引數提供的分隔符來分隔單詞,從而轉換字串的大小寫。
例如 −
如果輸入字串是 −
const str = 'thisIsAString'; const separator = '_';
那麼輸出字串應該是 −
const output = 'this_is_a_string';
示例
以下是程式碼 −
const str = 'thisIsAString';
const separator = '_';
const separateCase = (str = '', separator = ' ') => {
const arr = [];
let left = 0, right = 0;
for(let i = 0; i < str.length; i++){
const el = str[i];
const next = str[i + 1];
if((el.toUpperCase() === el && el.toUpperCase() !== el.toLowerCase()) || !next){
right = i + Number(!next);
};
if(left !== right){
const sub = str.substring(left, right).toLowerCase();
arr.push(sub);
left = right;
};
};
return arr.join(separator);
};
console.log(separateCase(str, separator));輸出
以下是在控制檯上的輸出 −
this_is_a_string
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP