As discussed in many questions on stack - IE 8 wont accept .trim()
, but the jQuery framework takes care of that.
I don't know how to translate my function to use that version of trim (I thought I was already using jQuery), could someone advise? Here is my code:
$('input').val(function(index, val){
return val.replace('Please Select', '').trim();
});
This is designed to replace the string with nothing.
I've tried:
$('input').val(function(index, val){
return val.replace('Please Select', '')$.trim();
});
but that was no good.
trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. If these whitespace characters occur in the middle of the string, they are preserved.
Answer: Use the jQuery $. trim() function You can use the jQuery $. trim() function to remove all the spaces (including non-breaking spaces), newlines, and tabs from the beginning and end of the specified string.
The trim() method removes whitespace from both ends of a string.
The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.
$.trim(val.replace('Please Select', ''))
http://api.jquery.com/jQuery.trim/
IE8 doesn't have a native trim
method, generally, I just augment the prototype:
if (!String.prototype.trim)
{
String.prototype.trim = function()
{
return this.replace(/^\s+|\s+$/g,'');
};
}
This is the shortest regex to trim a string, but I have heard it say that .replace(/^\s\s*/,'').replace(/\s*\s$/,'')
is (marginally) faster... the choice is yours
If you really want to use jQuery for this, of course, you'll have to make the target string the context of the called method ($.trim
calls the method on $
=== the jQuery object), so make the String a jQ object:
$(' foo bar ').trim();//returns "foo bar"
//compared to augmented prototype:
' foo bar '.trim();//returns "foo bar"
The benefit of an augmented prototype is that you don't have the additional overhead of creating a new jQuery object, whereas using the prototype-approach relies on JS to wrap the string in a native String object and apply the method to that. Basically, it's the same operation, but it should be a marginally more efficient, because jQuery does a bunch of checks to any string passed to the jQuery constructor ($()
)
Try this:
$.trim(val.replace('Please Select', ''));
Here's the Trim() entry in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With