Khaled Ramadan
Khaled Ramadan

Reputation: 183

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

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?

Upvotes: 3

Views: 143

Answers (6)

David Bray
David Bray

Reputation: 586

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())) //==> @

Upvotes: 0

i100
i100

Reputation: 4666

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.

Upvotes: 0

Sifat Haque
Sifat Haque

Reputation: 6057

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

Upvotes: 0

Titus
Titus

Reputation: 22474

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.

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

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

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 370779

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

Upvotes: 5

Related Questions