0

I'm using the below code to trim the string based on the condition like 15 characters per line, in this below code, 15 was hard-coded.But I need to make it dynamic like defining variable and pass into replace function.

var str = "Here's to your next step.Keep Walking.Keep Watching"
result = str.replace(/(.{1,15})(?:\n|$| )/g, "$1|\n");
console.log(result);

How I need

var trim_val =15;
var str = "Here's to your next step.Keep Walking.Keep Watching"
result = str.replace(/(.{1,trim_val})(?:\n|$| )/g, "$1|\n"); //here i have to pass that variable
console.log(result);

Thanks in Advance

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
robert
  • 21
  • 1
  • 6

1 Answers1

0

You need to use the RegExp constructor, to create a new Regex instance with your trim_val variable and use it in your replace() call.

This is how should be your code:

var trim_val = 15;
var str = "Here's to your next step.Keep Walking.Keep Watching";
var reg = new RegExp("(.{1,"+trim_val+"})(?:\n|$| )", "g");
var result = str.replace(reg, "$1|\n");

Demo:

var trim_val = 15;
var str = "Here's to your next step.Keep Walking.Keep Watching";
var reg = new RegExp("(.{1,"+trim_val+"})(?:\n|$| )", 'g');
var result = str.replace(reg, "$1|\n"); //here i have to pass that variable
console.log(result);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78