Member Avatar for SolidSolutions

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!

Member Avatar for jimforsyth

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

I know this is a really old post, but I just came across it recently, and just in case the jsfiddle becomes unavailable at any point in the future, what's written there is:

var num = "12345"; alert(num.charAt(num.length - 1));
Member Avatar for Biiim

Wheres the function!

function checkLastChar(string){ return string.charAt(string.length-1); } console.log(checkLastChar('testing')); function removeTrailingDot(string){ if(string.charAt(string.length-1) == '.'){ return string.slice(0, -1); }else{ return string; } } console.log(removeTrailingDot('something.')); console.log(removeTrailingDot('something'));

If you find yourself repeating the same code your doing it wrong.

Probably not an absolute truth but it is a pretty workable rule.

Be a part of the DaniWeb community

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