JavaScript Extract Substring from String

JavaScript Extract Substring from String

Extract substring from string without regex using javascript string.substring() method; In this tutorial, you will learn all about JavaScript string.substring() method and how to extract a substring from a string using this method.

JavaScript string.substring() method

The JavaScript string.substring() method returns the new sub string from a given string, the basis of the provided index.

The following syntax demonstrates substring() method:

str.substring(indexA [, indexB])

The string.substring() method takes 2 parameters: indexA and indexB:

  • The indexA is a position where to start the extraction.
  • The indexB  is a position where to end the extraction.

Remember some important things about substring() method:

  • If you ignore the indexB, the substring() returns the substring to the end of the string.
  • If indexA equals indexB, the substring() method returns an empty string.
  • If indexAis greater than the indexB, the substring() swaps their roles: the indexA becomes the indexB.
  • If either indexA or indexB is less than zero or greater than the string.length, the substring() considers it as zero (0).
  • If any parameter is NaN, the substring() treats it as if it were zero (0).

Examples: JavaScript substring() method

Let’s take look at some examples of string.substring() js string method.

1) Extracting a substring from the starting of the string

Extract a substring from the between two indexes of provided string, and return a new substring.

See the following example:

let string = 'Hello, Programmer';
let substring = string.substring(0,4);

console.log(substring);

Output:

Hello

2) Extracting a substring to the end of the string

The following example uses the javascript string.substring() to extract at position 6, and return a new sub string.

See the following example:

let string = 'Hello, Programmer';
let substring = string.substring(6);

console.log(substring);

Output:

Programmer

Conclusion

In this tutorial, you have learned all about JavaScript string.substring() method.

Recommended JavaScript Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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