Replace multiple strings with multiple other strings

前端 未结 18 2032
别那么骄傲
别那么骄傲 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:07

    Use numbered items to prevent replacing again. eg

    let str = "I have a %1, a %2, and a %3";
    let pets = ["dog","cat", "goat"];
    

    then

    str.replace(/%(\d+)/g, (_, n) => pets[+n-1])
    

    How it works:- %\d+ finds the numbers which come after a %. The brackets capture the number.

    This number (as a string) is the 2nd parameter, n, to the lambda function.

    The +n-1 converts the string to the number then 1 is subtracted to index the pets array.

    The %number is then replaced with the string at the array index.

    The /g causes the lambda function to be called repeatedly with each number which is then replaced with a string from the array.

    In modern JavaScript:-

    replace_n=(str,...ns)=>str.replace(/%(\d+)/g,(_,n)=>ns[n-1])
    

提交回复
热议问题