简体   繁体   English

在trim()之后获取字符串的最后一个字符不起作用

[英]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? 不知道如何解决这个问题?

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

这是因为emailWhiteSpace.trim()没有改变字符串,它返回一个新的,这意味着emailWhiteSpace.trim().lengthemailWhiteSpace.length

You can use trimEnd() to trim the last space. 您可以使用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]); 

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). 这是因为emailWhiteSpace.length返回一个未修剪的字符串(带有空格)。 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())) //==> @

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM