I had a difficult time figuring out how to get or test the last character of a string with javascript, so figured I would post it once I found out in case it helps someone else.

I found plenty of removing the last character, but not for just checking what the last character of a string is using javascript.

// create string
var str = new String("No Periods Allowed.");

// alternatively get string from field:
// var str = document.getElementById('textbox').value;

// show last character in the string
alert( str.charAt( str.length-1 ) );

// remove last character from string if a period
if(str.charAt( str.length-1 ) == ".") {
  alert( str.slice(0, -1) );

Well, finding that easily on a search would have saved me some time. Happy Coding!

Recommended Answers

All 2 Replies

Hi SolidSolutions,

You can also treat a string like an array, i.e.

/* Set string var */
var my_string = 'longboard';

/* Store last character of string */
var last_character = my_string[my_string.length-1];

/* Alert */
alert( last_character );

Jim :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.