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

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

问题描述

我认为trim()不存储调整后的值.

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

我在用户提交其字符串并对其起作用之前对结果应用修剪,它会通过删除多余的空间来正确显示.但是,如果我取回修整后的值,它会为我提供用户输入的原始内容,不会删除空间.

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天全站免登陆