在trim()之后获取字符串的最后一个字符不起作用 [英] Getting the last character of a string is not working after trim()

查看:77
本文介绍了在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@ "));

这篇关于在trim()之后获取字符串的最后一个字符不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆