Reshape String, inserting "\ n" for every N characters

Using JavaScript functions, I tried to insert a separator string into a string for every N characters provided by the user.

Similar: function("blabla", 3) would output "bla\nbla\n".

I searched for a lot of answers and got a regex for this, the only problem: I need user input on this question, so I need to bind a variable in this regex.

Here is the code:

function reshapeString(string, num) {
    var regex = new RegExp("/(.{" + num + "})/g");
    return string.replace(regex,"$1\n");
}

reshapeString("blablabla", 3);

This is currently not working. I tried to escape the "/" characters, but at some point I got scared and I don't know where.

What am I missing? Is there any other way to solve the problem of reformatting this line?

+4
source share
2 answers

regexp /, , $& .

function reshapeString(string, num) {
    var regex = new RegExp(".{" + num + "}", "g");
    return string.replace(regex,"$&\n");
}

console.log(reshapeString("blablabla", 3));
Hide result
+4

?

const reshapeString = (str,N) => str.split('').reduce((o,c,i) => o+(!i || i%N?'':'\n')+c, '')

:

  • ,
  • reduce(), ( .. , !)
  • i%N (.. ), N, o.
  • i%N 0 ( falsey ), :
    • o ( ) +
    • \n ( N '- )
    • c ( )
  • . !i, char,

Regex FSA. 1000

:

(_ => {
    const reshapeString_AP = (str,N) => str.split('').reduce((o,c,i) => o+(!i || i%N?'':'\n')+c, '')
    function reshapeString_Nina(string, num) {
        var regex = new RegExp(".{" + num + "}", "g");
        return string.replace(regex,"$&\n");
    }

    const payload = 'a'.repeat(100)
    console.time('AP');
    reshapeString_AP(payload, 4)
    console.timeEnd('AP');
    console.time('Nina');
    reshapeString_Nina(payload, 4)
    console.timeEnd('Nina');
})()

(3 ):

AP: 0.080078125ms
Nina: 0.13916015625ms
---
AP: 0.057861328125ms
Nina: 0.119140625ms
---
AP: 0.070068359375ms
Nina: 0.116943359375ms
+3

Source: https://habr.com/ru/post/1694066/


All Articles