License Key Formatting

LeetCode題目: 482. License Key Formatting

My solution:

/**
 * @param {string} s
 * @param {number} k
 * @return {string}
 */
let licenseKeyFormatting = (s, k) => {
    const combind = s.replace(/-/g, '').toUpperCase();
    if(combind.length <= k) return combind;
    const firstLength = combind.length % k;
    let result = firstLength !== 0 ? combind.slice(0, firstLength) + '-' : '';
    const otherKey = result ? combind.slice(firstLength) : combind;
    for(let i=0; i<otherKey.length; i++) {
        result += otherKey[i];
        if((i+1) % k === 0 && i !== otherKey.length - 1) result += '-';
    }
    return result;
}
profile-image
Hi, 我是 Zeki。目前為一名前端工程師。我相信科技始終來自於人性,是用來幫助人們過上更有品質的生活的,但願也希望如此。