Skip to content Skip to sidebar Skip to footer

Javascript get last characters from a URL or string

Reading Time: < 1 minute

How can I get last two characters or specific characters from a url or given string.If you have basic knowledge of javascript substring this is easy job.
First of all, look at this example.Then you can understand this better.
javascript get last characters from a string or url

Get specific characters from a url

//url like = http://www.example.com/category.php?id=12
var currentURL = window.location;
var chars = currentURL.href.substr(-2);
alert(chars); // 12

How can you get url parameters from url?

//url like = http://www.example.com/category.php?id=12&action=edit
param = document.location.href.split('?')[1];
alert(param); // id=12&action=edit

Get specific characters from a given string or text.

If you want to get last two characters from a string, you can get it like following example.

var charList = "This is an example";
var lastTwo  = charList.substr(charList.length - 2);
alert(lastTwo);

Following example is describes how is the behavior of sub string.This is get start from 2nd letter(here “a”) with get number of three characters.

var charList = "example";
alert(charList.substr(2,3));

Easy method

var myString = 'colomn1_Tabs1';
var lastFive = myString.substr(-5); // get from last "Tabs1"
alert(lastFive);