3

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

1
  • 1
    Try this ('function' + (args[1] || '')).replace(/function/, 'fn') Commented Dec 22, 2014 at 19:20

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.