如何从字符串中删除最终空格 [英] How to remove final space from string

查看:98
本文介绍了如何从字符串中删除最终空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个给定的字符串。在将其添加到数据库之前,我需要检查是否给出了最终空间。如果是,它应该删除它们。



我该怎么做?



我是什么尝试过:



我试过那个



I have a given string. Before adding it to the database, i need to check, if a final space is given. If yes it should delete them.

How can i do this?

What I have tried:

I tried that one

input.split(' ').join('');

。那个删除所有空格。

推荐答案

为了清除前导和尾随空格,有一个trim()方法...

还有trimEnd()和trimStart(),但有些浏览器不支持它们......

对于所有人都有正则表达式方法(trim()实际上是这个的包装器)。 ..

For cleaning both leading and trailing white-spaces there is a trim() method...
There is also trimEnd() and trimStart(), but some of the browsers does not support them...
For all there is the regex approach (trim() is actually a wrapper for this)...
input.replace(/\s+


/,' ');


Regex for this is overkill。对于这样一个简单的任务,不需要性能损失。我会说最快的是检查是否有最终空格然后更新;



Regex for this is overkill. There is no need for the performance hit for such a simple task. I would say the fastest is to check if there is a final space and then update;

private static bool CheckEndingBlank(ref string str)
{
    if (str[str.Length - 1] == ' ')
    {
        str = str.TrimEnd(' ');
        return true;
    }
    return false;
}





我在这里假设你确实想知道最后一个字符是否是空格并希望删除所有尾随空格。



I am assuming here that you really do want to know if the last character is a space and want to remove the all trailing spaces.


这篇关于如何从字符串中删除最终空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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