Getting the last character of a string is not working after trim()

Viewed 117

How to remove the white spaces from string, in order to get the last character?

const email = "abc@";
const emailWhiteSpace = "abc@ ";
console.log(email.trim()[email.length - 1]) //==> @
console.log(emailWhiteSpace.trim()[emailWhiteSpace.length - 1]) //==> undefinied

Any idea how to solve this issue?

6 Answers

It might be easier to use a regular expression - match a non-space character, followed by space characters, followed by the end of the line ($):

const lastChar = str => str.match(/(\S)(?=\s*$)/)[1];
console.log(lastChar("abc@"));
console.log(lastChar("abc@ "));

Of course, you can also save the trimmed text in a variable:

const lastChar = str => {
  const trimmed = str.trim();
  return trimmed[trimmed.length - 1];
};
console.log(lastChar("abc@"));
console.log(lastChar("abc@ "));

You need to also refer to the trimmed string when accessing the length:

const email = "abc@";
const emailWhiteSpace = "abc@ ";
console.log(email.trim()[email.length - 1]) //==> @
console.log(emailWhiteSpace.trim()[emailWhiteSpace.trim().length - 1])
//                                               ^^^^^^^^

But a better approach, which would have avoided your error in the first place, would be to just assign the trimmed string to an actual variable:

var emailWhiteSpace = "abc@ ";
var emailWhiteSpaceTrimmed = emailWhiteSpace.trim();
console.log(emailWhiteSpaceTrimmed[emailWhiteSpaceTrimmed.length - 1])

That is because emailWhiteSpace.trim() is not mutating the string, it return a new one which means that emailWhiteSpace.trim().length is not the same as emailWhiteSpace.length.

You can use trimEnd() to trim the last space.

const emailWhiteSpace = "abc@ ";
console.log(emailWhiteSpace.trimEnd()[emailWhiteSpace.trimEnd().length-1])

/*
  You can also use a separate variable 
*/
const trimmedEmail = emailWhiteSpace.trimEnd();
console.log(trimmedEmail[trimmedEmail.length-1]);

You've put trim on the wrong place. Should be

emailWhiteSpace[emailWhiteSpace.trim().length - 1] //-> "@"

This is because of the emailWhiteSpace.length returns an untrimmed string (with the whitespace). Thus you have either assign the trim result to some variable or to put it in the indexer as shown. This would depend on what are you're trying to achieve.

mine would be ..

const email = "abc@";
const emailWhiteSpace = "abc@ ";

const f = function( v) { v = String(v); return v[v.length-1]};

console.log( f( email.trim())) //==> @
console.log( f( emailWhiteSpace.trim())) //==> @
Related