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);
});
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);
});
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, ' '));
$(".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>
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.
You dont have any value of your input element therefore an empty string returned
http://jsfiddle.net/lakshay/5sufd9jj/1/
$(".button").click(function() {
var name = $( ".input" ).val();
name = $.trim(name);
$(".input").attr("value",name);\\To show the trimmed sring
});
String.prototype.trim()
const greeting = ' Hello world! ';
console.log(greeting); // expected output: " Hello world! ";
console.log(greeting.trim()); // expected output: "Hello world!";
Polyfill:
Running the following code before any other code will create trim() if it's not natively available.
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}