Reputation: 511
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
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
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
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