5

I have an excel spreadsheet that has 3 columns.

    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:

enter image description here

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.

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.

What am I doing wrong?

Any help is appreciated.

Grizzly
  • 5,873
  • 8
  • 56
  • 109

2 Answers2

10

I've changed your replace with a 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);
});
Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
Ralph Janssen
  • 106
  • 1
  • 6
0

Using a regular expression would replace any number of spaces.

$(document).ready(function() {
    var str = 'Your string';
    var stringWithoutSpace = str.replace(/\s/g, '')
});
jordiburgos
  • 5,964
  • 4
  • 46
  • 80
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114