JavaScript: Replace the first digit in a string (should contains at least digit) with $ character
JavaScript Basic: Exercise-136 with Solution
Replace First Digit in String with $
Write a JavaScript program to replace the first digit in a string (should have at least one digit) with the $ character.
Visual Presentation:
Sample Solution:
JavaScript Code:
/**
* Function to replace the first digit in a string with '$'
* @param {string} input_str - The input string
* @returns {string} - The modified string with the first digit replaced by '$'
*/
function replace_first_digit(input_str) {
// Using regular expression to replace the first occurrence of a digit with '$'
return input_str.replace(/[0-9]/, '$');
}
console.log(replace_first_digit("abc1dabc")); // Output: "abc$dabc"
console.log(replace_first_digit("p3ython")); // Output: "p$ython"
console.log(replace_first_digit("ab1cabc")); // Output: "ab$cabc"
Output:
abc$dabc p$ython ab$cabc
Live Demo:
See the Pen javascript-basic-exercise-136 by w3resource (@w3resource) on CodePen.
Flowchart:
ES6 Version:
/**
* Function to replace the first digit in a string with '$'
* @param {string} input_str - The input string
* @returns {string} - The modified string with the first digit replaced by '$'
*/
const replace_first_digit = (input_str) => {
// Using regular expression to replace the first occurrence of a digit with '$'
return input_str.replace(/[0-9]/, '$');
};
console.log(replace_first_digit("abc1dabc")); // Output: "abc$dabc"
console.log(replace_first_digit("p3ython")); // Output: "p$ython"
console.log(replace_first_digit("ab1cabc")); // Output: "ab$cabc"
Improve this sample solution and post your code through Disqus.
Previous: JavaScript program to remove all characters from a given string that appear more than once.
Next: JavaScript program to test if a given integer is greater than 15 return the given number, otherwise return 15.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics