Search code examples
javascripthtmlstringhtml-manipulation

String manipulation, replacing " " with (space)


I've been working on a function that changes the spaces between words into the string " "(space).

For example, "Hello World. Hi there." would become "Hello(space)world.(space)Hi(space)there."

EDIT: I'm trying to build this to a specific set of structured English which is as follows:

  • set the initial value of result to an empty string
  • for each index in the argument string
  • if the character at that index is a space then
  • append '(space)' to result
  • else
  • append the character at that index to result
  • end if
  • end for
  • return result

Here is what I was able to come up with so far.:

function showSpaces(aString)
{
var word, letter;

word = aString
for var (count = 0; count < word.length; count = count + 1)

{
    letter = word.charAt(count);
    if (letter == " ")
    {
        return("(space)");
    }
    else
    {
        return(letter);
    }
}
}

Whenever I test this function call, nothing happens:

<INPUT TYPE = "button" NAME = "showSpacesButton"  VALUE ="Show spaces in a string as (space)"
        ONCLICK = "window.alert(showSpaces('Space: the final frontier'));">

I'm just beginning with JavaScript at the moment. Any help would be appreciated.

-Ross.


Solution

  • Use String.replace

    function showSpaces(aString)
    {
        return aString.replace(/ /g,'(space)');
    }
    

    EDIT: to get your code working:

    function showSpaces (aString)
    {
    
        var word, letter,
            output = ""; // Add an output string
    
        word = aString;
        for (var count = 0; count < word.length; count = count + 1) // removed var after for
    
        {
            letter = word.charAt(count);
            if (letter == " ")
            {
                output += ("(space)"); // don't return, but build the string
            }
            else
            {
                output += (letter); // don't return, but build the string
            }
        }
        return output; // once the string has been build, return it
    
    }