Reputation: 690
Working with a expression i got from an api source code. Can't get it to work how they have it. Or, it is not working how I would expect.
//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
Question: Why is the replace not working in the #2? looking to get 'fn b' as a result in the one expression. myplunk thx
Upvotes: 3
Views: 58
Reputation: 944445
You are running the replacement on the string before you add "function"
to it:
(args[1] || '').replace(/function/, 'fn')
You need to add more parens.
('function' + (args[1] || '')).replace(/function/, 'fn')
Upvotes: 4