-3

Write a JavaScript program to replace all digit in a string with $ character.

function replace_first_digit(input_str) {
  return input_str.replace(/[0-9]/, '$');
}
console.log(replace_first_digit("abc1dabc"));
console.log(replace_first_digit("p3ytho2n"));
console.log(replace_first_digit("ab10cabc"));
Jamiec
  • 133,658
  • 13
  • 134
  • 193

4 Answers4

4

You need the addition of the g modifier to make the replace work on multiple matches

function replace_first_digit(input_str) {
  return input_str.replace(/[0-9]/g, '$');
}
console.log(replace_first_digit("abc1dabc"));
console.log(replace_first_digit("p3ytho2n"));
console.log(replace_first_digit("ab10cabc"));

However, the naming of the function as replace_first_digit makes me suspect that you might have misunderstood the requirement and your original code was correct!

Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

Use the g-modifier/flag

const replace_first_digit = input_str => input_str.replace(/[0-9]/g, '$');
console.log(replace_first_digit("abc1dabc"));
console.log(replace_first_digit("p3ytho2n"));
console.log(replace_first_digit("ab10cabc")); 
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

This will do the trick

function replace_first_digit(input_str) {
  return input_str.replace(/\d/g, '$');
}
console.log(replace_first_digit("abc1dabc"));
console.log(replace_first_digit("p3ytho2n"));
console.log(replace_first_digit("ab10cabc"));
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
0
function replace_all_digits(input_str) {
  return input_str.split('').map((i)=> isNaN(i) ? i : '$').join('')
}
console.log(replace_all_digits("abc1dabc"));
console.log(replace_all_digits("p3ytho2n"));
console.log(replace_all_digits("ab10cabc")); 

Iterates over each letter and checks if it can be a number. If so, returns a $ otherwise the letter.

Riza Khan
  • 2,712
  • 4
  • 18
  • 42