How to use javascripts replace () on dynamic string

Working with an expression obtained from the api source code. Can't get it to work like they have. Or it doesn't work as 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 expression construct)
console.log('function' + (args[1] || '').replace(/function/, 'fn'));  
// function b

      

Question: Why doesn't the replacement work at # 2? to get "fn b" in a single expression. myplunk thanks

+3
javascript regex


source to share


1 answer


You do the replacement on the string before adding "function"

to it:

(args[1] || '').replace(/function/, 'fn')

      



You need to add more parens.

('function' + (args[1] || '')).replace(/function/, 'fn')

      

+4


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics