1

I've looked up this question but am new to coding so I'm not quite able to relate other answers to this.

Given a string s, return a string
where all occurrences of its first char have been changed to '*', except do not change
the first char itself. e.g. 'babble' yields 'ba**le' Assume that the string is length 1 or more. Hint: s.replace(stra, strb) returns a version of string s where all instances of stra have been replaced by strb.

This is what I have, but this does not replace every character after except the first, it just replaces the next character.

function fixStart(s)
    {
  var c = s.charAt(0);
  return c + s.slice(1).replace(c, '*');
    }
Kat
  • 11
  • 4

2 Answers2

0

To replace all occurrences not just the first, you can use a RegExp:

function fixStart(s) {
    var c = s.charAt(0);
    return c + s.slice(1).replace(new RegExp(c, 'g'), '*');
}

For example if the value of c is "b", then new RegExp(c, 'g') is equivalent to /b/g.

This will work for simple strings like "babble" in your example. If the string may start with special symbols that mean something in regex, for example '.', then you will need to escape it, as @Oriol pointed out in a comment. See how it's done in this other answer.

Community
  • 1
  • 1
janos
  • 120,954
  • 29
  • 226
  • 236
0
  function fixStart(s) {
    var c = s.charAt(0);
    var outputStr = '';
    // literate through the entire string pushing letters into a new string unless it is the first letter
    for (var i = 0; i < s.length; i++) {
      // if the letter is the first letter AND we are not checking the first letter
      if (s[i] === c && i !== 0) outputStr += '*'
      else outputStr += s[i]
    }
    return outputStr;
  }

  console.log(fixStart('hellohahaha'))
joemillervi
  • 1,009
  • 1
  • 8
  • 18