11-Apr-2023
.
Admin
In this tute, we will discuss how to get first two characters of string in javascript. you'll learn how to get first two character of string. I would like to share with you how to get the first 2 characters of a string in javascript. We will use how to get the first two characters of a string in javascript.
You can use the `substring()` method to get the first two characters of a string in JavaScript. Here's an example:
Example 1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How to Get First Two Characters of String in Javascript? - NiceSnippets.Com</title>
</head>
<body>
</body>
<script type="text/javascript">
let str = "Hello World";
let firstTwoChars = str.substring(0, 2);
console.log(firstTwoChars); // Output: "He"
</script>
</html>
In this example, we declare a variable `str` with the value `"Hello World"`. We then use the `substring()` method to extract the first two characters of the string by passing in two arguments: the starting index (which is 0 for the first character) and the ending index (which is 2 for the second character). The resulting substring is stored in a new variable called `firstTwoChars`, which we then log to the console using `console.log()`.
#JavaScript