others - Javascript - trim()后,获取字符串的最后一个字符无效

如何删除字符串空格,获得最后一个字符?


const email ="abc@";


const emailWhiteSpace ="abc@";


console.log(email.trim()[email.length - 1]) //==> @


console.log(emailWhiteSpace.trim()[emailWhiteSpace.length - 1]) //==> undefinied



如何解决此问题?

时间:

使用正则表达式更容易-匹配非空格字符,后跟空格字符,后跟行($ )的末尾:


const lastChar = str => str.match(/(S)(?=s*$)/)[1];


console.log(lastChar("abc@"));


console.log(lastChar("abc@"));

当然,你还可以将 trim后的文本保存在变量中:


const lastChar = str => {


 const trimmed = str.trim();


 return trimmed[trimmed.length - 1];


};


console.log(lastChar("abc@"));


console.log(lastChar("abc@"));


const email ="abc@";


const emailWhiteSpace ="abc@";


console.log(email.trim()[email.length - 1]) //==> @


console.log(emailWhiteSpace.trim()[emailWhiteSpace.trim().length - 1])


// ^^^^^^^^

但是一个更好的方法,只是将trim过的字符串分配给一个实际的变量:


var emailWhiteSpace ="abc@";


var emailWhiteSpaceTrimmed = emailWhiteSpace.trim();


console.log(emailWhiteSpaceTrimmed[emailWhiteSpaceTrimmed.length - 1])

你可以使用trimEnd()修剪最后一个空格。


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

你trim错了地方。 应该是


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




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



...