Skip to content

Javascript substring method | Get Substring of given string example

  • by

Javascript substring Method is used to get the substring of the given String. Actually, the JS substring() method returns the part of the string between the start and end index.

Syntax

string.substring(start, end)

Parameters

  • indexStart (Start)Integer value will the first character to include in the returned substring.
  • indexEnd (End)– An optional integer value will the character to exclude from the returned substring.

Return value

It will return a new string containing the specified part of the given string.

Examples of Javascript substring method

The substring() method does not change the original given string.

Using Start and Stop indices

Begin the extraction at position 0, and extract up to 8 index of string:

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	const str = 'EyeHunts Tutorial';

			alert(str.substring(0, 8));
			// expected output: "EyeHunts"
        	
        </script>
    </head>
    
</html>

Output:

Examples of Javascript substring method

Get only the first character

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	const str = 'EyeHunts Tutorial';

			alert(str.substring(0,1));
			// expected output: "E"
        	
        </script>
    </head>
    
</html>

Output: E

Get only the last character:

<script type="text/javascript">
      var str = 'EyeHunts Tutorial';
      alert(str.substring(str.length - 1, str.length));
 // expected output: "l"
     	
</script>

Output: l

Q: What is the JavaScript substring indexof() method?

Answer: The indexOf() method returns the position of the first occurrence of a specified value in a string.

How to javascript substring after a character?

Answer: You can use String.slice with String.lastIndexOf to get substring after the last specific character in JavaScript.

See below example:-

var str = 'test/category/1';
str.slice(0, str.lastIndexOf('/') + 1);
// => "test/category/"
str.slice(str.lastIndexOf('/') + 1);
// => 1

Q: How to javascript substring before character?

Answer: Get substring before any char you can use a substring() and indexof() method in JS.

See below example how to use it.

var streetaddress= addy.substr(0, addy.indexOf(',')); 

OR

var string = "foo-bar-baz"
var splitstring = string.split('-')
//splitstring is a 3 element array with the elements 'foo', 'bar', and 'baz'

Do comment if you have any doubts and suggestions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *