为什么不.trim()真的修剪? [英] Why doesn't .trim() really trim?

查看:103
本文介绍了为什么不.trim()真的修剪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为 trim()不存储修剪后的值。

I think trim() doesn't store the trimmed value.

我在用户提交字符串之前对结果应用trim,它可以正常显示,删除多余的空格。但是,如果我返回修剪后的值,它会给我原始的用户输入,但不会删除空格。

I apply trim to the result before the user submits their string and it works, it displays properly by removing the extra space. But if I retrieve the trimmed value back, it gives me the original of user's input, it doesn't remove space.

在从输入字段中检索用户输入之前,我添加 trim()

Before I retrieve the user input from the input field, I added trim():

input = $("<input type='text'>").val(txt);
input.trim()

它不起作用。

推荐答案

你应该把它分回来,否则就没有意义了。

You should assign it back otherwise it's meaningless.

txt = txt.trim();
input = $("<input type='text'").val(txt);

注意:以上是使用原生JavaScript trim()方法,假设 txt 是纯字符串。如果您的网站应支持IE8及更低版本,请参阅此答案,了解如何添加此类支持。

Note: the above is using the native JavaScript trim() method, assuming txt is plain string. If your site should support IE8 and below, refer to this answer to see how to add such support.

根据OP评论进行更新。事实证明,请求是截断所有内部空间,就像HTML一样。为了实现这一点,加上更好的支持修改这一行:

Update, based on OP comments. Turns out the request is to truncate all inner spaces, same way HTML is doing. To achieve this, plus better support for the trim change this line:

var text = $(this).text();

到这三个:

var text = $.trim($(this).text());
while (text.indexOf("  ") > 0)
    text = text.replace("  ", " ");

更新了小提琴

这篇关于为什么不.trim()真的修剪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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