Home how to pass variable inside replace java-script function
Reply: 1

how to pass variable inside replace java-script function

seshadry
1#
seshadry Published in 2017-11-13 09:10:05Z

This question already has an answer here:

  • How do you use a variable in a regular expression? 16 answers

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

chsdk
2#
chsdk Reply to 2017-11-13 09:13:52Z

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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.333101 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO