Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using JavaScript functions, I was trying to insert a breakline on a string at every N characters provided by the user.

Just like this: function("blabla", 3) would output "bla\nbla\n".

I searched a lot of answers and ended up with a regex to do that, the only problem is, I need the user's input on the matter, so I need to stuck a variable on this regex.

Here's 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 I'm screwing up at some point and I don't know where.

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

like image 952
Platiplus Avatar asked Mar 06 '23 19:03

Platiplus


1 Answers

You need a string for the regexp constructor, without /, and you can omit the group by using $& for the found string.

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

console.log(reshapeString("blablabla", 3));
like image 150
Nina Scholz Avatar answered Mar 09 '23 11:03

Nina Scholz