Curtis W
Curtis W

Reputation: 511

How to simply pass a variable in a regex replace statement?

I have a variable string phrase, and I want to trim out the beginning of the string with contents from a variable, with or w/o a blank space.

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var result = fullphrase.replace("/^cutthis ?/i","");

I want result to be = "trim this phrase?"

How can I accomplish this?

Upvotes: 1

Views: 91

Answers (3)

sabof
sabof

Reputation: 8192

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var result = fullphrase.replace(new RegExp('^' + cutthis + ' ?', 'i') ,"");

Upvotes: 3

Ahmad Mageed
Ahmad Mageed

Reputation: 96487

To dynamically build the pattern use the RegExp object:

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var pattern = "^" + cutthis + " ?";
var re = new RegExp(pattern, "i");
var result = fullphrase.replace(re,"");
console.log(result);

Check out a JSBin demo of this in action.

Upvotes: 2

dab
dab

Reputation: 827

Why not pass the variable into the replace parameter?

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var result = fullphrase.replace(new RegExp("^" + cutthis + " ?", 'i'),"");

Upvotes: 3

Related Questions