Monday, July 12, 2021

Junior Developer Central JS Practice Exercise - 15

 
Question: 

Write a Javascript program to replace the first digit in a string with $ character. 




Answer: 

function replaceFirstDigit (str) {
const newStr = str.replace(/[0-9]/, '$'); 
console.log (newStr); 
}




> we declare a function 'replaceFirstDigit' 
> it has one parameter 'str' which is a string
> we need to replace only the first digit occurrence in the 'str' string with a '$' sign 
> we declare a variable 'newStr' 
> we initialize it with a value that we get by using the replace method on 'str' 
> we use the character class or ''RegExp [0-9] Expression'' to find the digit in 'str' 
> we do not use the modifier 'g' as it will search for all the digits
> we only want the first occurrence so we will use on '/[0-9]/' & not '/[0-9]/g'
> we use '$' sign as the replacement
> we then console.log the 'newStr' variable to get our answer

No comments:

Post a Comment