我正在尝试用多个其他单词替换字符串中的多个单词。字符串是“我有一只猫,一只狗和一只山羊”。
但是,它不会产生“我有一只狗,一只山羊和一只猫”,而是会产生“我有一只猫,一只猫和一只猫”。在JavaScript中是否可以同时用多个其他字符串替换多个字符串,以便产生正确的结果?
var str = "I have a cat, a dog, and a goat.";
str = str.replace(/cat/gi, "dog");
str = str.replace(/dog/gi, "goat");
str = str.replace(/goat/gi, "cat");
//this produces "I have a cat, a cat, and a cat"
//but I wanted to produce the string "I have a dog, a goat, and a cat".
我写了这个npm包stringinject https://www.npmjs.com/package/stringinject,它允许您执行以下操作
which will replace the {0} and {1} with the array items and return the following string
or you could replace placeholders with object keys and values like so: