繁体   English   中英

如何从jQuery中的变量中删除换行符和空白

[英]How to remove line breaks and white space from variable in jQuery

我找到了一些有关此问题的答案( 从文本中删除所有空白[重复]

但是,在我的情况下,没有一个答案有效。如果有空,请看看。

第一步,Mako和Python模板:为什么我在第一个空格中有换行和空白:

我们正在使用Mako模板和Python在我们的视图中生成数据:

<!-- The Python def on the page that pulls in the correct id -->
<%def name="pull_id(contact)">
    % if "member" in contact:
        ${contact["member"]["id"]}
    % else:
        ${contact["id"]}
    % endif
</%def>

<%def name="render_contact_row(contact)">

    <!-- the def returns the id here -->
    <tr data-contact-id='${pull_id(contact)}'>

最初,我直接在<tr>标记中包含Python代码,但是生成了可见的换行符。 现在至少使用<%def可以将所有内容保持在一行上,但是HTML中仍然有几个额外的空白

在此处输入图片说明

现在我的jQuery:

$('.btn_hide').live("click", function(event) {

    // gets the id number from the data tag in html
    var $tr = $(this).closest("tr");
    var id = $tr.data('contact-id');

    // tried this
    id.replace(/ /g,'');

    // then this
    id.replace(/\s+/, "");

    // even this
    id.replace(/\s/g, "");

    // still prints out white space :'(
    console.log(id);

    //...
});

当它命中console.log行chrome时会打印出来:

在此处输入图片说明

显然有换行符和额外的空格

最后,它再次命中Python:

@view_config(route_name="contacts_hide", request_method='POST')
def hide(self):
    id = self.param("id")
    if id is None:
        id = self.request.body
        if id.isdigit() is True:
            id = int(id)
        if id is None:
            raise Exception("The contact id parameter cannot be null!")

我在self.param上遇到了问题,因此它将跳过该问题并点击id = self.request.body行。

在此处输入图片说明

当然也要加入换行符和多余的空格:'( 在此处输入图片说明

请帮忙!

如果将过滤后的值分配回变量,则任何示例都将起作用:

var id = $tr.data('contact-id');
id = id.replace(/ /g, '');

但是我建议您改用$.trim方法:

var id = $.trim( $tr.data('contact-id') );

它将从值的开头和结尾删除空格。

最终,Python具有strip方法,其功能完全相同:

id = id.strip()

暂无
暂无

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

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