Here's an alternative way to achieve the same result without using regular expressions:
s = "The soldiers marched *, *, *, *.";
f = Function("words", "var i = 0; return \"" + s.split("*").join(
"\" + words[(i++) % words.length] + \""
) + "\";");
> | f(["L", "R"])
< | "The soldiers marched L, R, L, R."
> | f(["L", "R"].reverse())
< | "The soldiers marched R, L, R, L."
> | f(["L", "R", "R"])
< | "The soldiers marched L, R, R, L."
However, be cautious of potential malicious code:
s = "The soldiers marched *, *, *, *.";
s = "\", console.log(\"VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!\"), \"" + s;
f = Function("words", "var i = 0; return \"" + s.split("*").join(
"\" + words[(i++) % words.length] + \""
) + "\";");
> | f(["L", "R"])
| VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!
< | "The soldiers marched L, R, L, R."
Always make sure to sanitize user input:
s = "The soldiers marched *, *, *, *.";
s = "\", alert(\"VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!\"), \"" + s;
s = s.split("\"").join("\\\""); // may not be completely secure!
f = Function("words", "var i = 0; return \"" + s.split("*").join(
"\" + words[(i++) % words.length] + \""
) + "\";");
> | f(["L", "R"])
< | "", alert("VIRUS ATTACK!!! CALL +XX-XXXXX-XXXXX NOW!!!"), "The soldiers marched L, R, L, R."
Remember, it's always best to err on the side of caution when handling user input :-|