如何在jQuery中去除变量的换行和空白字符

1 投票
1 回答
6270 浏览
提问于 2025-04-17 23:10

我在网上找到了一些关于这个问题的回答(去掉文本中的所有空格 [重复]),

不过没有一个答案在我的情况下有效,如果你有时间请看看……

第一步 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)}'>

最开始我把 Python 代码直接放在 <tr> 标签里,但那样会产生可见的换行。现在使用 <%def 至少可以把它们保持在一行上,但 HTML 中还是有一些多余的空格。

enter image description here

现在我的 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 会打印出这个:

enter image description here

显然有换行和多余的空格

最后又回到 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

enter image description here

当然又带来了换行和多余的空格 :'(
enter image description here

请帮帮我!

1 个回答

6

你给出的任何例子都可以用,只要把过滤后的值重新赋值给变量就行:

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

不过我建议你使用 $.trim 方法,这样更好:

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

这个方法会把值开头和结尾的空格去掉。

最后,Python 也有一个 strip 方法,它的功能完全一样:

id = id.strip()

撰写回答