-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
  • 128,537
  • 12
  • 134
  • 188

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
  • 128,537
  • 12
  • 134
  • 188
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
  • 112,400
  • 31
  • 139
  • 174
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,627
  • 1
  • 7
  • 17
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
  • 1,934
  • 2
  • 12
  • 28