[英]Javascript - String replace by multiple strings
I'm wondering if a function exists that does this thing: 我想知道是否存在执行此操作的函数:
var greetings = "Hello %s, I'm %s"
greeting.replace('Mickey','Minnie');
// Should return: Hello Mickey, I'm Minnie
EDIT 编辑
Thank you all for the help! 谢谢大家的帮助!
I created a little node package for it, in case anyone needed something like this: 我为它创建了一个小节点程序包,以防万一有人需要这样的东西:
You can use template literals in an IIFE: 您可以在IIFE中使用模板文字 :
const greetings = ((a, b) => `Hello ${a}, I'm ${b}`)('Mickey','Minnie'); console.log(greetings);
If you're not able to use ES6 (template literals) or a polyfill, you can also pass a function to .replace()
. 如果您不能使用ES6(模板文字)或polyfill,还可以将函数传递给.replace()
。
See: 看到:
var greeting = "Hello %s, I'm %s"
var replacements = ['Mickey', 'Minnie'];
greeting.replace(/%s/g, function() {
return replacements.shift();
});
This returns "Hello Mickey, I'm Minnie" 这将返回“你好米奇,我是米妮”
Using just "traditional" Javascript: 仅使用“传统” JavaScript:
var greetings = "Hello %s, I'm %s"
(['Mickey','Minnie']).forEach (function (n) { greetings = greetings.replace ('%s', n) });
Thanks for you all! 谢谢大家!
I created a little node package for it, in case anyone needed something like this: 我为它创建了一个小节点程序包,以防万一有人需要这样的东西:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.