0

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!

Edited by SolidSolutions: n/a

3
Contributors
2
Replies
15
Views
6 Years
Discussion Span
Last Post by lucascaixeta
0

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 :)

Edited by jimforsyth: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.