# JavaScript: Replace the first digit in a string (should contains at least digit) with \$ character

## JavaScript Basic: Exercise-136 with Solution

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿