Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY - Trim Function Not Working

Tags:

jquery

trim

input

The trim function does not work correctly

<input class="input"></input>
<div class="button">CLICK</div>



$(".button").click(function() {

    var name = $( ".input" ).val(); 

    name = $.trim(name);

    console.log("TRIM " + name);    
});

http://jsfiddle.net/5sufd9jj/

like image 522
user3411039 Avatar asked Dec 29 '25 05:12

user3411039


2 Answers

Trim removes whitespace from the beginning and end of a string.

If you want to remove consecutive spaces such as 'string string', use the following:

$.trim(name.replace(/\s+/g, ' '));

Updated Example

$(".button").on('click', function() {
    var name = $.trim($('input').val().replace(/\s+/g, ' '));
    console.log("TRIM " + name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="input"></input>
<div class="button">CLICK</div>
like image 171
Josh Crozier Avatar answered Jan 02 '26 01:01

Josh Crozier


It is working all right.

trim function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

It DOES NOT remove spaces from the middle.

like image 33
Walt Avatar answered Jan 02 '26 02:01

Walt