Reputation: 40633
var prefix = 'pre-',
number = 1,
combined = prefix + number,
prefixRemoved = combined.replace('/' + prefix + '/g', '');
console.debug(prefixRemoved);
How do I remove prefix
from combined
? I'm still getting pre-1
as a result.
Upvotes: 1
Views: 1335
Reputation: 82554
You need to create the RegExp object:
var prefix = 'pre-',
number = 1,
combined = prefix + number,
prefixRemoved = combined.replace(new RegExp(prefix, 'g'), '');
console.debug(prefixRemoved);
Why that is happening:
// this syntax without quotes is shorthand for creating a RegExp object
typeof /aaaa/; // object
/a/ instanceof RegExp; // true
// since String.replace can take a string or a RegExp, it has to assume that any string is just a string
typeof "/aaaa/"; // string
Upvotes: 1
Reputation: 34855
You need prefixRemoved = combined.replace(prefix, '');
var prefix = 'pre-',
number = 1,
combined = prefix + number,
prefixRemoved = combined.replace(prefix, '');
console.debug(prefixRemoved);
Just call the variable directly.
Example: http://jsfiddle.net/jaffc/
Upvotes: 0
Reputation: 72961
There's really no need for using regular expressions since you are merely performing string replacement.
prefixRemoved = combined.replace(prefix, '');
See it in action: http://jsfiddle.net/jjYC8/
Upvotes: 0
Reputation: 707158
You can just pass a string to replace()
like this:
prefixRemoved = combined.replace(prefix, '');
or if you need parameters on the regular expression, you can create a regexp from a string like this:
prefixRemoved = combined.replace(new RegExp(prefix, "g"), '');
or, you can create the regex object first:
var re = new RegExp(prefix, "g");
prefixRemoved = combined.replace(re, '');
Upvotes: 1
Reputation: 219920
You don't need a regex for this. Simply use the string as is:
var prefix = 'pre-',
number = 1,
combined = prefix + number,
prefixRemoved = combined.replace(prefix, '');
console.debug(prefixRemoved);
Upvotes: 0