JavaScript Substring: The Hidden Gem to Supercharge Your Web Development Skills
JavaScript is a powerful language for web development, but one feature often goes unnoticed: JavaScript substring. In this blog post, we'll explore how JavaScript substring can enhance your web development skills with ease and provide you with practical examples to get started.
# Extracting a Portion of a String
Let's say you have a string variable called sentence with the "Hello, world!". With JavaScript substring, you can extract a specific portion of this string.
/*
This will give you "Hello", which extracts
characters from index 0 to 4 (inclusive).
*/
var sentence = "Hello";
var sub_str = sentence.substring(0, 5)
console.log(sub_str);
# Example 2: Getting Part of a URL
Imagine you have a URL stored in a variable called URL with the value "https://www.example.com/article/12345". You can easily retrieve the article ID from the URL using a JavaScript substring.
/*
This will give you "12345", extracting the portion
of the string after the last "/" character.
*/
var url = "https://www.example.com/article/12345";
var article_id = url.substring(url.lastIndexOf('/') + 1);
console.log(article_id);