How do I trim a string in JavaScript? That is, how do I remove all whitespace from the beginning and the end of the string in JavaScript?
Use the Native JavaScript Methods: String.trimLeft(), String.trimRight(), and String.trim().
String.trim()
is supported in IE9+ and all other major browsers:
' Hello '.trim() //-> 'Hello'
String.trimLeft()
and String.trimRight()
are non-standard, but are supported in all major browsers except IE
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
IE support is easy with a polyfill however:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}
Here's a very simple way:
function removeSpaces(string){
return string.split(' ').join('');
}
Don't know what bugs can hide here, but I use this:
var some_string_with_extra_spaces=" goes here "
console.log(some_string_with_extra_spaces.match(/\S.*\S|\S/)[0])
Or this, if text contain enters:
console.log(some_string_with_extra_spaces.match(/\S[\s\S]*\S|\S/)[0])
Another try:
console.log(some_string_with_extra_spaces.match(/^\s*(.*?)\s*$/)[1])
The trim from jQuery is convenient if you are already using that framework.
$.trim(' your string ');
I tend to use jQuery often, so trimming strings with it is natural for me. But it's possible that there is backlash against jQuery out there? :)
Simple version here What is a general function for JavaScript trim?
function trim(str) {
return str.replace(/^\s+|\s+$/g,"");
}
I know this question has been asked three years back.Now,String.trim()
was added natively in JavaScript.For an instance, you can trim directly as following,
document.getElementById("id").value.trim();