JavaScript RegEx: Format string with dynamic length to block format

前端 未结 3 1281
情深已故
情深已故 2021-01-21 08:45

The following RegEx formats given string to following output block pattern:

123 456 78 90 (= 3 digits 3 digits 2 digits 2 digits )

RegEx:



        
3条回答
  •  执笔经年
    2021-01-21 09:10

    anubhava's and Wiktor's solutions are clever, but I don't think I'd use a regular expression to do it; the solutions feel too complex to maintain. (This is a judgement call.) Here's an approach that gets the individual digits and inserts spaces after the third digit and after every subsequent digit whose index position is an odd number:

    result = [...str].map((d, i) => d + (i === 2 || (i >= 5 && i % 2 === 1) ? " " : "")).join("");
    

    Live Example:

    const tests = [
        ["1234", "123 4"],
        ["1234567", "123 456 7"],
        ["123456789", "123 456 78 9"],
        ["1234567890123", "123 456 78 90 12 3"],
    ];
    
    function format(str) {
        return [...str].map((d, i) => d + (i === 2 || (i >= 5 && i % 2 === 1) ? " " : "")).join("");
    }
    
    for (const [str, expected] of tests) {
        const result = format(str);
        console.log(`|${str}|`, "=>", `|${result}|`, result === expected ? "OK" : "*** ERROR");
    }

    Here's a version that works in ES5-only environments:

    result = str.split("").map(function(d, i) {
        return d + (i === 2 || (i >= 5 && i % 2 === 1) ? " " : "");
    }).join("");
    

提交回复
热议问题