简体   繁体   English

如何从字符串jQuery中删除多个空格

[英]How To Remove Multiple Spaces from String jQuery

I have an excel spreadsheet that has 3 columns. 我有一个包含3列的Excel电子表格。

    1st        |    2nd    |    3rd 
----------------------------------------
  xxxxxxxx           x        xxxxxxxx

When I copy all 3 of those cells and paste them into my textbox I get a value that looks likes this: 当我复制所有这三个单元格并将它们粘贴到我的文本框中时,我得到一个看起来像这样的值:

在此输入图像描述

I need to eliminate the spaces, but what I have researched isn't working. 我需要消除空间,但我研究的是不起作用。

Here is what I have: 这是我有的:

$(document).ready(function() {
    $("#MyTextBox").blur(function() {
        var myValue = $(this).val();
        alert(myValue);
        var test = myValue.replace(' ', '');
        alert(test);
        $("#MyTextBox").val(test);

    });
});

When I alert test it looks the exact same as the original and the value for MyTextBox isn't being replaced. 当我提醒test它看起来与原始完全相同,并且MyTextBox的值没有被替换。

I have a JSFiddle where I'm trying to replicate the issue, but in this instance, only the 1st space is replaced but the new value is populating into the textbox. 我有一个JSFiddle ,我试图复制该问题,但在这个例子中,只有第一个空格被替换,但新值填充到文本框中。

What am I doing wrong? 我究竟做错了什么?

Any help is appreciated. 任何帮助表示赞赏。

I've changed your replace with a regex . 我用regex改变了你的替换。 This removes all the spaces 这将删除所有空格


$("#MyTextBox").blur(function(){
    var myValue = $(this).val();
    alert(myValue);
    var test = myValue.replace(/\s/g, '');
    alert(test);
    $("#MyTextBox").val(test);
});

Using a regular expression would replace any number of spaces. 使用正则表达式将替换任意数量的空格。

$(document).ready(function() {
    var str = 'Your string';
    var stringWithoutSpace = str.replace(/\s/g, '')
});

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

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