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!

Dani AI

Generated

Nice tip. A couple of additions that may save future readers time:

  • Prefer primitive strings over new String(...). A literal like const str = "No Periods Allowed."; avoids surprising behavior because boxed String objects are not strictly equal to primitives. See MDN on the String object for caveats (MDN).

  • To read the last character without branching, slice(-1) is concise and safely returns "" for an empty string:

const last = str.slice(-1);

In modern engines you can also use at(-1) for negative indexing (ES2022), which reads a single code unit (MDN):

const last = str.at(-1);
  • To remove a trailing period without an if, a regex anchored to the end of the string is simple and avoids extra slicing:
const withoutTrailingDot = str.replace(/\.$/, "");

(MDN replace)

  • Unicode note: most methods above operate on UTF-16 code units. If you need the last user-perceived character (e.g., emoji or letters with combining marks), segment into grapheme clusters first:
const lastGrapheme = [...str].pop() || "";

For full accuracy across locales, consider Intl.Segmenter with granularity: "grapheme" (MDN).

Recommended Answers

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

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

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.