[英]how to use javascripts replace() on a dynamic string
Working with a expression i got from an api source code. 使用我从api源代码获得的表达式。 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? 问题:为什么替换不在#2中工作? looking to get 'fn b' as a result in the one expression. 希望得到'fn b'作为一个表达式的结果。 myplunk thx myplunk thx
You are running the replacement on the string before you add "function"
to it: 在向其添加"function"
之前,您正在对字符串运行替换:
(args[1] || '').replace(/function/, 'fn')
You need to add more parens. 你需要添加更多的parens。
('function' + (args[1] || '')).replace(/function/, 'fn')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.