Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to get the first three characters of a string using JavaScript ?

  • Last Updated : 08 Jun, 2021

The following approach covers how to find the 3 letters of the string, here we will use the days’ name as a string by using JavaScript for a given date.

Example:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

Input:  today
Output: SUN

Input: tomorrow
Output: MON

Input: yesterday
Output: SAT

Input: 01-04-2021
Output: THU

Approach:

  • First, get the current date using the new Date( ) and store it into a variable (date).
  • If the input date is tomorrow the using setDate() method increases one date to the Date(), if the input date is yesterday the decrease one date from the Date().
  • And if the value is not today then we pass the input date to the Date() object. That’s why if the user inputs today then the Date() will be the default and the default Date() object depicts today’s Date().
  • Now by using the date.getDay() method we get the day of the date. It will return a number ranging from 0-6 where 0 represents Sunday and 6 represents Saturday and the remaining days lie in order. Create an array containing the days of the week. By using the index get the preferred day name.
  • By using the slice method extract the Beginning three characters.

Example: Create an index.js file and write down the following code.



index.js

<script>
// Javascript program to get three  beginning characters of the day

function getDay(d) {
    let date = new Date();
    let days = ["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY",
        "THURSDAY", "FRIDAY", "SATURDAY"]

    if (d === "tomorrow") {
        date.setDate(date.getDate() + 1)
    } else if (d === "yesterday") {
        date.setDate(date.getDate() - 1)
    } else if (d != "today") {
        date = new Date(d);
    }

    // Get the todays day
    let day = days[date.getDay()]

    // Extract three characters from the beginning
    let threeCharDay = day.slice(0, 3)

    // Print or return the three character day
    console.log(threeCharDay)
}

// Function calls
getDay("yesterday")
getDay("today")
getDay("tomorrow")
getDay("2021-03-30")
getDay("2021-03-31")
getDay("2021-04-01")
</script>

Run the index.js file using the following command:

node index.js

Output: 

MON
TUE
WED
TUE
WED
THU
My Personal Notes arrow_drop_up
Recommended Articles
Page :