[英]how to use javascripts replace() on a dynamic string
使用我从api源代码获得的表达式。 无法让它工作如何拥有它。 或者,它没有按照我的预期工作。
//original expression
// returns an anonymous function signature for example 'function(a, b)'
var args = ['a', 'b', 'c'];
return 'function ' + (args[1] || '').replace('/[\s\r\n]+/', ' ');
//1 - this works
var args = ['a', 'b', 'c'];
var string1 = 'function ' + (args[1] || '');
console.log(string1.replace(/function/, 'fn'));
// fn b
//2- this.does not(using the api's expression construct)
console.log('function' + (args[1] || '').replace(/function/, 'fn'));
// function b
问题:为什么替换不在#2中工作? 希望得到'fn b'作为一个表达式的结果。 myplunk thx
在向其添加"function"
之前,您正在对字符串运行替换:
(args[1] || '').replace(/function/, 'fn')
你需要添加更多的parens。
('function' + (args[1] || '')).replace(/function/, 'fn')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.