Skip to content
Advertisement

Replace a single character in a string

I am trying to make a function that automatically generated a response to a selection of an action in a text adventure game. My problem is that I have to replace every second ‘_’ with ‘ ‘. However I have tried everything I have though of and whenever I google the question the only solution I get is to use .replace(). However .replace() replaces every instance of that character. Here is my code, could you please fix this for me and explain how you fixed it.

JavaScript

Advertisement

Answer

Here’s one approach:

JavaScript

The result:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement