JavaScript - 使用变量替换子字符串

时间:2011-09-21 02:03:56

标签: javascript

var prefix = 'pre-',
    number = 1,
    combined = prefix + number,
    prefixRemoved = combined.replace('/' + prefix + '/g', '');
console.debug(prefixRemoved);

如何从prefix删除combined?我的结果仍然是pre-1

5 个答案:

答案 0 :(得分:1)

您可以像这样将字符串传递给replace()

prefixRemoved = combined.replace(prefix, '');

或者如果你需要正则表达式的参数,你可以从这样的字符串创建一个正则表达式:

prefixRemoved = combined.replace(new RegExp(prefix, "g"), '');

或者,您可以先创建正则表达式对象:

var re = new RegExp(prefix, "g");
prefixRemoved = combined.replace(re, '');

答案 1 :(得分:1)

您需要创建RegExp对象:

var prefix = 'pre-',
    number = 1,
    combined = prefix + number,
    prefixRemoved = combined.replace(new RegExp(prefix, 'g'), '');
console.debug(prefixRemoved);

Example


为什么会这样:

// 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

答案 2 :(得分:0)

你不需要正则表达式。只需按原样使用字符串:

var prefix = 'pre-',
    number = 1,
    combined = prefix + number,
    prefixRemoved = combined.replace(prefix, '');
console.debug(prefixRemoved);

答案 3 :(得分:0)

由于您只是执行字符串替换,因此实际上不需要使用正则表达式。

prefixRemoved = combined.replace(prefix, '');

查看实际操作:http://jsfiddle.net/jjYC8/

答案 4 :(得分:0)

您需要prefixRemoved = combined.replace(prefix, '');

var prefix = 'pre-',
    number = 1,
    combined = prefix + number,
    prefixRemoved = combined.replace(prefix, '');
console.debug(prefixRemoved);

直接调用变量。

示例: http://jsfiddle.net/jaffc/