StackOverflowNewbie
StackOverflowNewbie

Reputation: 40633

JavaScript - replace substring using a variable

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

Answers (5)

Joe
Joe

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

Example


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

Jason Gennaro
Jason Gennaro

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

Jason McCreary
Jason McCreary

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

jfriend00
jfriend00

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

Joseph Silber
Joseph Silber

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

Related Questions