Replace multiple strings with multiple other strings

前端 未结 18 2433
别那么骄傲
别那么骄傲 2020-11-22 04:14

I\'m trying to replace multiple words in a string with multiple other words. The string is \"I have a cat, a dog, and a goat.\"

However, this does not produce \"I ha

18条回答
  •  天命终不由人
    2020-11-22 05:11

    Just in case someone is wondering why the original poster's solution is not working:

    var str = "I have a cat, a dog, and a goat.";
    
    str = str.replace(/cat/gi, "dog");
    // now str = "I have a dog, a dog, and a goat."
    
    str = str.replace(/dog/gi, "goat");
    // now str = "I have a goat, a goat, and a goat."
    
    str = str.replace(/goat/gi, "cat");
    // now str = "I have a cat, a cat, and a cat."
    

提交回复
热议问题