Javascript Get First Character from String Example

04-Apr-2023

.

Admin

Javascript Get First Character from String Example

This article will give you example of javascript get first character from string. We will use javascript get first character of string. Here you will learn get first character of string javascript. I’m going to show you about find first character of string javascript. follow bellow step for select first character of string javascript.

There are several ways to get the first character from a string in JavaScript. Here are some examples:

Example 1: Using the charAt() method:


<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Javascript Get First Character from String Example</title>

</head>

<body>

</body>

<script type="text/javascript">

const str = "hello";

const firstChar = str.charAt(0);

console.log(firstChar); // Output: "h"

</script>

</html>

Example 2: Using array indexing:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Javascript Get First Character from String Example</title>

</head>

<body>

</body>

<script type="text/javascript">

const str = "world";

const firstChar = str[0];

console.log(firstChar); // Output: "w"

</script>

</html>

Example 3: Using the substring() method:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Javascript Get First Character from String Example</title>

</head>

<body>

</body>

<script type="text/javascript">

const str = "example";

const firstChar = str.substring(0, 1);

console.log(firstChar); // Output: "e"

</script>

</html>

Note that all of these methods return a string containing only the first character of the original string.

#JavaScript