Replacing spaces with characters?

Im trying to replace multiple spaces with a single space ;_; its not working aaaa

   This function receives a string. It also takes an optional character, which should default to an undrscore ('_') when not given.
    
    It should return the same string, but with all groups of whitespace (spaces, tabs and line breaks) replaced by a single instance of the character in the second argument.

    replaceWhitespaceWithCharacter('Hi Mum!', '•')
        returns 'Hi•Mum!'

    replaceWhitespaceWithCharacter('   do   not   
                enter               ')
        returns '_do_not_enter_'

    */

function replaceWhitespaceWithCharacter (str, character) {
  
  /* This function receives a string. It also takes an optional character, which should default to an undrscore ('_') when not given.
    
    It should return the same string, but with all groups of whitespace (spaces, tabs and line breaks) replaced by a single instance of the character in the second argument.

    replaceWhitespaceWithCharacter('Hi Mum!', '•')
        returns 'Hi•Mum!'

    replaceWhitespaceWithCharacter('   do   not   
                enter               ')
        returns '_do_not_enter_'
    */
    console.log(str)
    str = str.replace(/\s*/g,' ')
    
   console.log(str)
   str = str.split('')
   console.log(str)

    for(var i = 0 ; i<str.length ; i++)
    {
      if(str[i].match(/\s/))
      {
         str.splice(i,1,character)

      }

        
    }


 
    str.shift()
    str = str.join('')
    

    
    console.log(str)
    
    return str
}




replaceWhitespaceWithCharacter( '    yo   yo', '*')

image

Hint:

  • *--->Matches the preceding item x 0 or more times.
  • \s*–> matches 0 spaces or more than 0 spaces .
  • replace* with + ---->Matches the preceding item x1or more times. So use \s+
    OR,
  • you can use {} notation i-e {n,} —> Where n is a positive integer. Matches at least n occurrences of the preceding item x. So here use\s{2,}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

\s instead of /s

1 Like

:sweat_smile: thank you for pointing it out…edited that :+1: