DEV Community

Tandap Noel Bansikah
Tandap Noel Bansikah

Posted on

Simple JavaScript Challenges with solutions

As a programmer, or maybe a JavaScript developer, there are some simple challenges you face maybe in an interview or maybe with your own project. In this article, I will be taking you through two simple JavaScript challenges and their solutions.

String length and Retrieving the Number.

In a website, you might see a section that is been given to the user to write some text and there is always a limit to the number of characters they are supposed to write, so in this example we will be seeing a simple JavaScript code that can calculate the number of characters entered by the user and the number of characters remaining.

// prompt the user to enter a tweet
var tweet = prompt("Compose your tweet");

// count the length of character entered
var tweetCount = tweet.lenght;

// display output
alert("You have written " + tweetCount + "Characters ,and you have " + (140 - tweetCount) + " Characters remaining")
Enter fullscreen mode Exit fullscreen mode

Slice and extracting Parts of a string.

Let's consider another example where you will prompt the user to enter their name, and the code we are to write is supposed to convert the first letter of their name and display with a greeting message like hello name.

// prompt the user to enter name
var name = prompt("What is your name");

// extract first letter of name
var firstChar = name.slice(0,1);
//convert first letter to uppercase
var upperCaseFirstChar = firstChar.toUpperCase();
//extract remaing letters of name
var restOfChar = name.slice(1,name.length);
//convert remaining letters of name to lowercase in case the user write a name like this noEl
restOfChar = restOfChar.toLowerCase();
//join the first letter and other letters
var combined  = upperCaseFirstChar + restOfChar;
alert("Hello " + combined);
Enter fullscreen mode Exit fullscreen mode

Okay, that's the two I have got for now but there are other challenges like fizzBuzz and so many others and you can try to figure out other methods in which you can achieve the same goal. Thanks for you time. Adios

Top comments (0)