Getting The Last Character Of A String Is Not Working After Trim()
Solution 1:
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 ($
):
constlastChar = 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:
constlastChar = str => {
const trimmed = str.trim();
return trimmed[trimmed.length - 1];
};
console.log(lastChar("abc@"));
console.log(lastChar("abc@ "));
Solution 2:
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])
Solution 3:
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
.
Solution 4:
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]);
Solution 5:
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.
Post a Comment for "Getting The Last Character Of A String Is Not Working After Trim()"