Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Remove Multiple Spaces from String jQuery

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.

like image 638
Grizzly Avatar asked Nov 15 '17 15:11

Grizzly


People also ask

How can remove multiple space from string in jquery?

Use JavaScript's string. replace() method with a regular expression to remove extra spaces. The dedicated RegEx to match any whitespace character is \s .

How do you convert multiple spaces to single space?

The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.

How do I remove multiple spaces between words in JavaScript?

Answer: Use the JavaScript replace() method You can simply use the JavaScript replace() to replace the multiple spaces inside a string.

How do I trim a space between strings in JavaScript?

JavaScript String trim()The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.


1 Answers

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);
});
like image 116
Ralph Janssen Avatar answered Sep 19 '22 17:09

Ralph Janssen