如何在里面传递变量替换java-script函数

时间:2017-11-13 09:10:05

标签: javascript jquery regex variables

我正在使用下面的代码根据每行15个字符的条件修剪字符串,在下面的代码中,15是硬编码的。但是我需要使它像动态一样定义变量并传递给替换函数

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

我需要的方式

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);

先谢谢

1 个答案:

答案 0 :(得分:0)

您需要使用 RegExp constructor ,使用trim_val变量创建新的Regex实例,并在replace()调用中使用它。

这应该是你的代码:

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");

<强>演示:

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);